此题并不是一道简单的题,我采用的方法先从前序的第一个根节点开始,根据中序中的位置划分左子树右子树,再分别递归处理。我这种写法比传索引差一些。传索引会非常省时间。实际可以采用传索引的方法。
# 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: return
def process(root, preorder, inorder):
if not preorder: return
root.val = preorder[0]
pos = inorder.index(root.val)
if pos > 0:
root.left = TreeNode()
process(root.left, preorder[1:pos+1], inorder[:pos])
if pos+1 < len(preorder):
root.right = TreeNode()
process(root.right, preorder[pos+1:], inorder[pos+1:])
root = TreeNode()
process(root, preorder, inorder)
return root