Skip to content

Commit be864ec

Browse files
author
Joseph Luce
authored
Update 538_convert_BST_to_greater_tree.md
1 parent 5e33222 commit be864ec

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

leetcode/easy/538_convert_BST_to_greater_tree.md

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,3 +42,29 @@ class Solution:
4242
self._convert_bst_helper(root)
4343
return root
4444
```
45+
46+
## Iterative Solution
47+
- Runtime: O(N)
48+
- Space: O(N)
49+
- N = Number of nodes in BST
50+
51+
```
52+
class Solution:
53+
54+
def convertBST(self, root: TreeNode) -> TreeNode:
55+
stack = list()
56+
curr_node = root
57+
greater_vals = 0
58+
while True:
59+
if curr_node is not None:
60+
stack.append(curr_node)
61+
curr_node = curr_node.right
62+
elif len(stack) > 0: # At a leaf node
63+
curr_node = stack.pop()
64+
greater_vals += curr_node.val
65+
curr_node.val = greater_vals
66+
curr_node = curr_node.left
67+
else: # At a leaf node and stack is empty
68+
break
69+
return root
70+
```

0 commit comments

Comments
 (0)