-
Notifications
You must be signed in to change notification settings - Fork 0
/
453_Flaten_Binary_Tree_to_Linked_List.py
53 lines (46 loc) · 1.46 KB
/
453_Flaten_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
__author__ = "Wangdu Lin"
__copyright__ = "Copyright 2018, The Algorithm Project"
__credits__ = ["Wangdu Lin, jiuzhang"]
__license__ = "GPL"
__version__ = "1.0.1"
__maintainer__ = "Wangdu Lin"
__email__ = "[email protected]"
__status__ = "Production"
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
this.val = val
this.left, this.right = None, None
"""
class Solution:
"""
@param: root: a TreeNode, the root of the binary tree
@return:
"""
def flatten(self, root):
# the stop condition
if root is None:
return
self.flatten(root.left)
self.flatten(root.right)
# root pass it's memory address to p, therefore, they hold the same address
p = root
if p.left is None:
return
"""
In order to focus on dealing the left node, so current p move to the p.left. Right now p has different address with root.
"""
p = p.left
# print(id(root))
"""
This while loop is tring to move the current node to the end of the root.left's bottom right node.
"""
while p.right:
p = p.right
"""
This p var is holding the root.left, or if p.right is not None then holding root.left.right....right.right.right, which means it depend on above statement.
"""
p.right = root.right
root.right = root.left
root.left = None