Flatten Binary Tree to Linked List - LeetCode

Flatten Binary Tree to Linked List - LeetCode

题目:

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

分析:

我们观察这个转化,可以发现其实就是一个先序遍历的顺序,这样就好做了,但是一开始的时候我在如何在root本身上加右子节点也是考虑很久,此方法在root node上直接操作,先暂时保存左右子树,如果root有左子树,把root.right附城root.left,root.left归null,再在已经是右子树的左子树上找rightmost 的node,把之前存住的right子树放在rightmost.right上即可。做完一遍以后,这时root的左子树已经已经被嫁接到了右子树和root之间,原来的左子树变成null,可以进行root.right的递归了。这个方法我也是看别人博客上来的,在这个地址方面的控制绕了好久。。。

代码:

class Solution:
    # @param root, a tree node
    # @return nothing, do it in place
    def flatten(self, root):
        if not root:
            return None
        left = root.left
        right = root.right
        
        if left != None:
            root.right = left
            root.left = None
            rightmost = left
            while rightmost.right != None:
                rightmost = rightmost.right             
            rightmost.right = right
        self.flatten(root.right)


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值