二叉树展开为链表 (Flatten Binary Tree to Linked List)

 

思路:递归

// @Title: 二叉树展开为链表 (Flatten Binary Tree to Linked List)
// @Author: qisiii
// @Date: 2024-09-25 17:22:17
// @Runtime: 0 ms
// @Memory: 41.2 MB
// @comment: 递归
// @flag: GREEN
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 * int val;
 * TreeNode left;
 * TreeNode right;
 * TreeNode() {}
 * TreeNode(int val) { this.val = val; }
 * TreeNode(int val, TreeNode left, TreeNode right) {
 * this.val = val;
 * this.left = left;
 * this.right = right;
 * }
 * }
 */
class Solution {
    public void flatten(TreeNode root) {
        solution(root);
    }

    public TreeNode solution(TreeNode prev) {
        if(prev==null){
            return prev;
        }
        //中-左-右
        //中先指向左,然后递归计算左子树,让中指针指向左子树的最后一个
        //中再指向右,然后递归计算右子树,最终返回右子树的最后
        TreeNode right=prev.right;
        TreeNode left=prev.left;
        if(left!=null){
            prev.right=left;prev.left=null;
            prev=solution(left);
        }
        if(right!=null){
            prev.right=right;prev.left=null;
            prev=solution(right);
        }
        return prev;
    }
}

思路:

// @Title: 二叉树展开为链表 (Flatten Binary Tree to Linked List)
// @Author: qisiii
// @Date: 2024-09-25 17:20:05
// @Runtime: 0 ms
// @Memory: 41 MB
// @comment: 
// @flag: 
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 * int val;
 * TreeNode left;
 * TreeNode right;
 * TreeNode() {}
 * TreeNode(int val) { this.val = val; }
 * TreeNode(int val, TreeNode left, TreeNode right) {
 * this.val = val;
 * this.left = left;
 * this.right = right;
 * }
 * }
 */
class Solution {
    public void flatten(TreeNode root) {
        solution(root);
    }

    public TreeNode solution(TreeNode prev) {
        if(prev==null){
            return prev;
        }
        TreeNode right=prev.right;
        TreeNode left=prev.left;
        if(left!=null){
            prev.right=left;prev.left=null;
            prev=solution(left);
        }
        if(right!=null){
            prev.right=right;prev.left=null;
            prev=solution(right);
        }
        return prev;
    }
}
Licensed under CC BY-NC-SA 4.0
最后更新于 2024-10-18