-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy path005_bstFromPreorder.py
More file actions
28 lines (27 loc) · 869 Bytes
/
005_bstFromPreorder.py
File metadata and controls
28 lines (27 loc) · 869 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
28
# 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 preorder == None:
return []
root = TreeNode(preorder[0])
for i in preorder[1:]:
cur = root
while cur!=None:
if i < cur.val:
if cur.left == None:
cur.left = TreeNode(i)
break
else:
cur = cur.left
elif i > cur.val:
if cur.right == None:
cur.right = TreeNode(i)
break
else:
cur = cur.right
return root