forked from luliyucoordinate/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0105.py
41 lines (34 loc) · 1.09 KB
/
0105.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
40
41
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def buildTree(self, preorder, inorder):
"""
:type preorder: List[int]
:type inorder: List[int]
:rtype: TreeNode
"""
if not inorder or not preorder:
return
root = TreeNode(preorder[0])
stack = [root]
i = 0
for node in preorder[1:]:
parent = stack[-1]
if parent.val != inorder[i]:
parent.left = TreeNode(node)
stack.append(parent.left)
else:
while stack and stack[-1].val == inorder[i]:
parent = stack.pop()
i += 1
parent.right = TreeNode(node)
stack.append(parent.right)
return root
if __name__ == "__main__":
preorder = [3,9,20,15,7]
inorder = [9,3,15,20,7]
Solution().buildTree(preorder, inorder)