-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuildTree.py
More file actions
30 lines (27 loc) · 991 Bytes
/
buildTree.py
File metadata and controls
30 lines (27 loc) · 991 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
29
30
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> Optional[TreeNode]:
seen = set()
def buildTree(inorder):
if not inorder: return None
if len(inorder) == 1:
seen.add(inorder[0])
return TreeNode(inorder[0])
root, val = None, None
for num in preorder:
if num not in seen:
root = TreeNode(num)
val = num
break
if root:
seen.add(val)
ind = inorder.index(val)
root.left = buildTree(inorder[:ind])
root.right = buildTree(inorder[ind+1:])
return root
return buildTree(inorder)