输入某二叉树的前序遍历和中序遍历的结果,请构建该二叉树并返回其根节点。
假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
示例 1:
Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
Output: [3,9,20,null,null,15,7]
示例 2:
Input: preorder = [-1], inorder = [-1]
Output: [-1]
限制:
0 <= 节点个数 <= 5000
python解法如下:
# 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:
n = len(preorder)
if n == 0: return None
if n == 1: return TreeNode(preorder[0])
//二叉树的根节点就是前序遍历序列的第一个节点
root = TreeNode(preorder[0])
index = inorder.index(root.val)
root.left = self.buildTree(preorder[1:index + 1], inorder[ :index] )
root.right = self.buildTree(preorder[index + 1:n], inorder[index + 1:n])
return root