1. 重建二叉树
输入某二叉树的前序遍历和中序遍历的结果,请重建该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字
方法:
class TreeNode:
def __init__(self, val=0):
self.val = val
self.left = None
self.right = None
def buildTree(preorder, inorder):
if len(preorder) == 0:
return None
root_val = preorder[0]
cur_node = TreeNode(root_val)
root_index = inorder.index(root_val)
cur_node.left = buildTree(preorder[1:root_index + 1], inorder[:root_index])
cur_node.right = buildTree(preorder[root_index + 1:], inorder[root_index + 1:])
return cur_node