每日一题:LeetCode之二叉树展开为链表

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

      1
     / \
     2  5
    / \  \
   3   4  6

将其展开为:

         1
          \
           2
            \
             3
              \
               4
                \
                 5
                  \
                   6 

思路: 对当前结点,左子树(node.left)挂到右孩子处,再找左子树中最右边的孩子,将右子树(node.right)挂在这个最右边孩子的右子树处。

 private TreeNode pre;
    public void flatten(TreeNode root) {
       while(root!=null){
           if(root.left==null)
                root=root.right;
            else{
                TreeNode pre=root.left;
                while(pre.right!=null)
                    pre=pre.right;
                pre.right=root.right;
                root.right=root.left;
                root.left=null;
                
                root=root.right;
            }
       }
    }
发布了28 篇原创文章 · 获赞 0 · 访问量 362

猜你喜欢

转载自blog.csdn.net/qq_40053995/article/details/105204078