-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1008.py
39 lines (31 loc) · 961 Bytes
/
1008.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
# 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) -> TreeNode:
nodes = [TreeNode(x) for x in preorder]
current = None
root = None
stack = []
for node in nodes:
if current is None:
root = node
current = node
continue
if node.val < current.val:
current.left = node
stack.append(current)
current = node
else:
pop = None
while stack and stack[-1].val < node.val:
pop = stack.pop()
if pop:
current = pop
current.right = node
current = node
stack.append(current)
return root