给定一棵二叉树的先序遍历及中序遍历,尝试构建该二叉树。
说明:
例如:
preorder = [3,9,20,15,7]
inorder = [9,3,15,20,7]
3
/ \
9 20
/ \
15 7
题目出处:LeetCode
本文采用递归方式实现:
https://github.com/leileiluoluo
func buildTree(preorder []int, inorder []int) *TreeNode {
if 0 == len(preorder) {
return nil
}
root := preorder[0]
i := 0
for ; i < len(inorder); i++ {
if root == inorder[i] {
break
}
}
return &TreeNode{
Val: root,
Left: buildTree(preorder[1:i+1], inorder[:i]),
Right: buildTree(preorder[i+1:], inorder[i+1:]),
}
}
https://github.com/leileiluoluo
class Solution:
def build_tree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
if 0 == len(preorder):
return None
val = preorder[0]
for i in range(len(inorder)):
if val == inorder[i]:
break
node = TreeNode(val=val)
node.left = self.build_tree(preorder[1:1 + i], inorder[:i])
node.right = self.build_tree(preorder[1 + i:], inorder[i + 1:])
return node