-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmorris_traversal.py
85 lines (73 loc) · 2.88 KB
/
morris_traversal.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
from typing import (
Optional,
)
from solutions.binary_tree.tree_node import (
TreeNode,
)
# Time Limit Exceeded on leetcode.
class MorrisSolutionVersionOne:
def morris_traversal(self, root: Optional[TreeNode]) -> list[int]:
current = root
ret_list = []
while current:
# If left child is null, update
# the current pointer to right child.
if current.left:
current = current.right
ret_list.append(current.val)
else:
# Find the inorder predecessor
previous = current.left
if previous:
while previous.right and previous.right != current:
previous = previous.right
# If the right child of inorder
# predecessor already points to
# the current node, update the
# current with it's right child
if not previous.right:
previous.right = current
current = current.left
# else If right child doesn't point
# to the current node, then update the right child
# pointer with the current node and update
# the current with it's left child
else:
previous.right = None
current = current.right
if current:
ret_list.append(current.val)
return ret_list
class MorrisSolutionVersionTwo:
def morris_traversal(self, root: Optional[TreeNode]) -> list[int]:
# Set cursor to root of binary tree
def helper(root: Optional[TreeNode]) -> int:
current = root
while current:
print(current.val)
if current.left:
yield current.value
current = current.right
else:
# Find the inorder predecessor of cursor
previous = current.left
while True:
if previous:
if not previous.right:
previous.right = current
current = current.left
break
if previous.right is current:
previous.right = None
current = current.right
break
previous = previous.right
else:
break
return list(helper(root))
MorrisSolutionVersionOne = MorrisSolutionVersionOne
MorrisSolutionVersionTwo = MorrisSolutionVersionTwo
__all__ = [
"MorrisSolutionVersionOne",
"MorrisSolutionVersionTwo",
]