题目:
重建二叉树:输入某二叉树的前序遍历和中序遍历的结果,请重建该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
思路:
简单
程序:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:
if not preorder or not inorder:
return None
tree_root = TreeNode(preorder.pop(0))
tree_root_index = inorder.index(tree_root.val)
tree_root.left = self.buildTree(preorder, inorder[: tree_root_index])
tree_root.right = self.buildTree(preorder, inorder[tree_root_index + 1 : ])
return tree_root