-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path114 Flatten Binary Tree to Linked List.py
127 lines (107 loc) · 2.76 KB
/
114 Flatten Binary Tree to Linked List.py
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
"""
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.
Hints:
If you notice carefully in the flattened tree, each node's right child points to the next node of a pre-order traversal.
Author: Rajeev Ranjan
"""
# Definition for a binary tree node
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def __repr__(self):
return repr(self.val)
class Solution:
def flatten_data_structure(self, root):
"""
:param root: TreeNode
:return: nothing, do it in place
"""
# trivial
if not root:
return
lst = []
self.dfs_traverse(root, lst)
lst = lst[1:] # exclude root
root.left = None
cur = root
for node in lst:
node.left = None
node.right = None
cur.right = node
cur = cur.right
def dfs_traverse(self, root, lst):
"""
pre_order traverse
"""
if not root:
return
lst.append(root)
self.dfs_traverse(root.left, lst)
self.dfs_traverse(root.right, lst)
def flatten(self, root):
"""
pre-order should be easy
flatten left subtree
flatten right subtree
root->left->right
in-order is harder to flatten
http://fisherlei.blogspot.sg/2012/12/leetcode-flatten-binary-tree-to-linked.html
:param root:
:return:
"""
if not root:
return None
left_last = self.get_last(root.left)
left = self.flatten(root.left)
right = self.flatten(root.right)
# left_last = left
# while left_last and left_last.right:
# left_last = left_last.right
root.left = None
if left:
root.right = left
left_last.right = right
else:
root.right = right
return root
def get_last(self, root):
"""
pre-order last
:param root:
:return:
"""
if not root:
return None
if not root.left and not root.right:
return root
if root.right:
return self.get_last(root.right)
else:
return self.get_last(root.left)
if __name__=="__main__":
node1 = TreeNode(1)
node2 = TreeNode(2)
node1.left = node2
Solution().flatten(node1)