题目
给定两种遍历,构造二叉树
preorder = [3,9,20,15,7]
inorder = [9,3,15,20,7]
思路
根据先序遍历找root节点,到中序里找到root节点的index,然后再到中序遍历里找左右,然后递归。
代码
def built_tree(pre,inorder):
if inorder:
root_index = inorder.index(pre.pop(0))
root = Node(inorder[root_index])
root._left = built_tree(pre,inorder[0:root_index])
root._right = built_tree(pre,inorder[root_index+1:])
return root