首页 > 代码库 > Leetcode 114, Flatten Binary Tree to Linked List

Leetcode 114, Flatten Binary Tree to Linked List

根据提示,本题等价于pre order traverse遍历,并且依次把所有的节点都存成right child,并把left child定义成空集。用递归的思想,那么如果分别把左右子树flatten成list,我们有:

    1

  /    \

 2     5

  \       \

   3      6 <- rightTail

     \

      4  <- leftTail

所以使用递归的解法一: 注意由于右子树最后要接到左子树的后面,所以用temp保存右子树的head。

 

 1 def flatten(self, root):
 2         """
 3         :type root: TreeNode
 4         :rtype: void Do not return anything, modify root in-place instead.
 5         """       
 6         if not root:
 7             return         
 8         self.flatten(root.left)
 9         self.flatten(root.right)
10         
11         temp = root.right
12         
13         root.right = root.left
14         root.left = None
15         
16         while root.right:
17             root = root.right
18         
19         root.right = temp

 

Leetcode 114, Flatten Binary Tree to Linked List