Skip to content

Commit 87d091d

Browse files
author
Joseph Luce
authored
Create 1008_construct_binary_search_tree_from_preorder_traversal.md
1 parent 97b9b72 commit 87d091d

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
## Recursive Solution
2+
3+
- Runtime: O(N^2)
4+
- Space: O(1)
5+
- N = Number of elements in array
6+
7+
I've selected this question because it would be good to know at least one reconstruction method of a BST.
8+
Preorder traversal was selected because it is one of the easier ones to understand.
9+
Unlike the other traversals, preorder has a property of knowing what the root node is by looking at the first element of the list.
10+
11+
Since we are reconstructing a BST and not a binary tree, we can identify which sections are the left and right subtree by comparing their values to the first element.
12+
The left subtree will have values less/equal than the root and right subtree will have values greater than the root.
13+
14+
```
15+
# Definition for a binary tree node.
16+
# class TreeNode:
17+
# def __init__(self, x):
18+
# self.val = x
19+
# self.left = None
20+
# self.right = None
21+
22+
class Solution:
23+
def bstFromPreorder(self, preorder: List[int]) -> TreeNode:
24+
25+
def bst_helper(preorder):
26+
if len(preorder) == 0:
27+
return None
28+
transition_index = len(preorder)
29+
for index, node in enumerate(preorder):
30+
if node > preorder[0]:
31+
transition_index = index
32+
break
33+
root = TreeNode(preorder[0])
34+
root.left = bst_helper(preorder[1:transition_index])
35+
root.right = bst_helper(preorder[transition_index:])
36+
return root
37+
38+
return bst_helper(preorder)
39+
```

0 commit comments

Comments
 (0)