Repository navigation
Expand file tree
/
Copy pathmorris_traversal.py
More file actions
82 lines (65 loc) · 2.12 KB
/
Copy pathmorris_traversal.py
File metadata and controls
82 lines (65 loc) · 2.12 KB
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
"""Morris Traversal of a Binary Tree.
Video
-----
* https://youtu.be/wGXB9OWhPTg
Analysis
--------
* Time complexity O(n)
* Space complexity O(1)
"""
from binary_tree import BinaryTree
class MorrisTraversal:
def __init__(self):
pass
@staticmethod
def find_predecessor(current):
predecessor = current.left
while predecessor.right != current and predecessor.right is not None:
predecessor = predecessor.right
return predecessor
@staticmethod
def inorder(root_node):
current = root_node
while current is not None:
if current.left is None:
print "{data} ".format(data=current.data),
current = current.right
else:
predecessor = MorrisTraversal.find_predecessor(current)
if predecessor.right is None:
predecessor.right = current
current = current.left
else:
predecessor.right = None
print "{data} ".format(data=current.data),
current = current.right
@staticmethod
def preorder(root_node):
current = root_node
while current is not None:
if current.left is None:
print "{data} ".format(data=current.data),
current = current.right
else:
predecessor = MorrisTraversal.find_predecessor(current)
if predecessor.right is None:
print "{data} ".format(data=current.data),
predecessor.right = current
current = current.left
else:
predecessor.right = None
current = current.right
if __name__ == '__main__':
bt = BinaryTree()
root = None
root = bt.add_head(10, root)
root = bt.add_head(50, root)
root = bt.add_head(-10, root)
root = bt.add_head(7, root)
root = bt.add_head(9, root)
root = bt.add_head(-20, root)
root = bt.add_head(30, root)
mt = MorrisTraversal()
mt.inorder(root)
print "\n",
mt.preorder(root)