*LeetCode-Flatten Binary Tree to Linked List

35 篇文章 0 订阅
22 篇文章 0 订阅

感觉这个题像前序遍历,但是其实完全按preorder的话 我只能想到用两个stack 太不好了

看到用stack的iterative 入stack顺序和preorder不一样,才能保证出来的时候是这个顺序

即先push right 再push left,pop之后的右子设置为当前stack top

这个里面强调不要忘记将左子设置为null;

   public void flatten(TreeNode root) {        if (root == null) return;
        Stack<TreeNode> stk = new Stack<TreeNode>();
        stk.push(root);
        while (!stk.isEmpty()){
            TreeNode curr = stk.pop();
            if (curr.right!=null)  
                 stk.push(curr.right);
            if (curr.left!=null)  
                 stk.push(curr.left);
            if (!stk.isEmpty()) //这里很重要,虽然while判断了stack是否空,但是最开始pop了
                 curr.right = stk.peek();
            curr.left = null;  // dont forget this!! 
        }
    }


后面这个是不是用栈的方法,只用o(1)space 但是不好想 

votes
1,290 views
class Solution {
public:
    void flatten(TreeNode *root) {
        TreeNode*now = root;
        while (now)
        {
            if(now->left)
            {
                //Find current node's prenode that links to current node's right subtree
                TreeNode* pre = now->left;
                while(pre->right)
                {
                    pre = pre->right;
                }
                pre->right = now->right;
                //Use current node's left subtree to replace its right subtree(original right 
                //subtree is already linked by current node's prenode
                now->right = now->left;
                now->left = NULL;
            }
            now = now->right;
        }
    }
};



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值