Construct Binary Tree from Preorder and Inorder Traversal
Construct Binary Tree from Preorder and Inorder Traversal
题目
Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
思路
根据先序遍历和中序遍历建树,建立根节点,然后划分左子树和右子树。递归
解题
c++ 版
1 | /** |
python版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# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param {integer[]} preorder
# @param {integer[]} inorder
# @return {TreeNode}
def buildTree(self, preorder, inorder):
return self.solve(preorder,0,inorder,0,len(inorder)-1)
def solve(self,preorder,p,inorder,low,high):
if low>high:
return None
root=TreeNode(preorder[p])
pos=0
for i in range(low,high+1):
if preorder[p]==inorder[i]:
pos=i
break
root.left=self.solve(preorder,p+1,inorder,low,pos-1)
root.right=self.solve(preorder,p+pos-low+1,inorder,pos+1,high)
return root