leetcode【每日一题】114. 二叉树展开为链表 Java

题干

给定一个二叉树,原地将它展开为一个单链表。

例如,给定二叉树

    1
   / \
  2   5
 / \   \
3   4   6
将其展开为:

1
 \
  2
   \
    3
     \
      4
       \
        5
         \
          6

想法

原地展开
可以老思路,先先序遍历,存在数组,完事再一个个取出来放到root的右子树即可。
当然
因为先序遍历本质
是左子树完了再右子树
可以根据这个点去找左子树的最后一个右子树
他就是他的右子树的前边的节点
这里不再展示代码

Java代码

/**
 * 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) {
        List<TreeNode> list=new LinkedList<>();
        helper(list,root);
        int size=list.size();
        for (int i=1;i<size;i++){
            TreeNode pre=list.get(i-1);
            TreeNode cur=list.get(i);
            pre.right=cur;
            pre.left=null;
        }

    }

    public  void helper(List<TreeNode> list,TreeNode root){
        if(root!=null) {
            list.add(root);
            helper(list, root.left);
            helper(list, root.right);
        }
    }

}

我的leetcode代码都已经上传到我的githttps://github.com/ragezor/leetcode

猜你喜欢

转载自blog.csdn.net/qq_43491066/article/details/107741584