-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconstructbst.py
More file actions
33 lines (30 loc) · 868 Bytes
/
Copy pathconstructbst.py
File metadata and controls
33 lines (30 loc) · 868 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
31
32
33
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def buildTree(self, preorder, inorder):
"""
:type preorder: List[int]
:type inorder: List[int]
:rtype: TreeNode
"""
if not len(inorder) or not len(preorder):
return None
treeVale = preorder.pop(0)
root = TreeNode(treeVale)
index = inorder.index(treeVale)
root.left = self.buildTree(preorder,inorder[:index])
root.right = self.buildTree(preorder,inorder[index+1:])
return root
def printtree(root):
if root == None:
return
printtree(root.left)
print root.val
printtree(root.right)
s = Solution()
root = s.buildTree([2,1,3],[1,2,3])
printtree(root)