LeetCode:114.Flatten Binary Tree to Linked List

题目的要求大体如下:

Given a binary tree, flatten it to a linked list in-place.

For example,
Given

     1
    / \
   2   5
  / \   \
 3   4   6

The flattened tree should look like:
1
 \
  2
   \
    3
     \
      4
       \
        5
         \
          6
click to show hints.

大体的意思就是给祢一棵二叉树,要求把它变成有斜树,即结点的左子树接到右边且右子树接在后面。

一.我的解法

我的想法是既然要将左子树接到右边,那么用后序遍历会比较好。从下往上,从左到右地进行合并。比较要注意一点的是要留一个指针使其指向左子树的叶子,之后再在左子树的后面接上右子树。时间复杂度是O(n)。

class Solution {
    public void flatten(TreeNode root) {
        helper(root);
    }
    public TreeNode helper(TreeNode root){
        if(root==null) return null;
        TreeNode left=helper(root.left);
        TreeNode right=helper(root.right);
        if(left!=null)
        {
            TreeNode node=left;
            while(node.right!=null)
            {
                node=node.right;
            }
            root.right=left;
            node.right=right;
            root.left=null;
        }
        else{
            root.right=right;
            root.left=null;
        }
        return root;
    }
}

二.扩展

1)同样是用递归的方法,但是是通过反向的先序遍历,并且维护一个前指针,用来合并左右子树。
时间复杂度是O(n)。
这个是原地址:
https://discuss.leetcode.com/topic/11444/my-short-post-order-traversal-java-solution-for-share

class Solution{
    TreeNode pre=null;
    public void flatten(TreeNode root){
        if(root==null) return;
        flatten(root.right);
        flatten(root.left);
        root.right=pre;
        root.left=null;
        pre=root;
    }
}

2)其实这道还可以用迭代的方法来解决,思路是和之前的解法一样,只是这次更加直接,不是从下往上,而是从上往下的进行合并。从右子树出发,只要该节点没有左子树就没有必要进行合并继续向下遍历,否则进行合并操作。
时间复杂度也是O(n)。
这是原地址:
https://discuss.leetcode.com/topic/3995/share-my-simple-non-recursive-solution-o-1-space-complexity

class Solution{
    public void flatten(TreeNode root){
        if(root==null) return;
        TreeNode node=root;
        while(node!=null)
        {
            if(node.left!=null)
            {
                TreeNode tail=node.left;
                while(tail.right!=null) tail=tail.right;
                tail.right=node.right;
                node.right=node.left;
                node.left=null;
            }
            node=node.right;
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值