flatten binary tree to linked list

这题主要是用recursion的想法,假设函数已经把所有的问题都解决好了,剩下的只要解决当前层的问题就可以了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class (object):
def flatten(self, root):
"""
:type root: TreeNode
:rtype: void Do not return anything, modify root in-place instead.
"""
self.flat(root)
def flat(self, root):
# it is like preorder traversal
if not root:
return None
right = root.right
root.right = self.flat(root.left)
root.left = None
head = root
while head.right:
head = head.right
head.right = self.flat(right)
return root