-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1008.py
More file actions
27 lines (26 loc) · 834 Bytes
/
1008.py
File metadata and controls
27 lines (26 loc) · 834 Bytes
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
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def bstFromPreorder(self, preorder: List[int]) -> TreeNode:
if not preorder:
return []
root = TreeNode(preorder.pop(0))
def helper(root, val):
if not root:
return
if not root.left and val < root.val:
root.left = TreeNode(val)
elif not root.right and val > root.val:
root.right = TreeNode(val)
if root.val < val:
helper(root.right, val)
else:
helper(root.left,val)
return root
while preorder:
helper(root, preorder.pop(0))
return root