-
Notifications
You must be signed in to change notification settings - Fork 2
/
ConvertBSTToGreaterTree.py
66 lines (55 loc) · 1.38 KB
/
ConvertBSTToGreaterTree.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
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def __init__(self):
self.total = 0
# Recursion
def convertBST(self, root: TreeNode) -> TreeNode:
# Perform a "in order traversal", but starting from right to left
if root:
self.convertBST(root.right)
self.total += root.val
root.val = self.total
self.convertBST(root.left)
return root
# Iteration
def convertBST_iteration(self, root: TreeNode) -> TreeNode:
if not root:
return None
stack = []
total = 0
current = root
while True:
while current:
stack.append(current)
current = current.right
if not stack:
return root
node = stack.pop()
total += node.val
node.val = total
current = node.left
########
# Test #
########
# 5
# / \
# 2 13
root = TreeNode(5)
node1 = TreeNode(2)
node2 = TreeNode(13)
root.left = node1
root.right = node2
# new_root = Solution().convertBST(root)
new_root = Solution().convertBST_iteration(root)
assert new_root.val == 18
assert new_root.left.val == 20
assert new_root.right.val == 13
print("OH, YEAH!")
# 18
# / \
# 20 13