最后将构造好的树的根节点返回即可,利用index函数找到中序遍历中根节点位置
# 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:
# 记住递归结束的条件,not preorder或 not inorder
if not preorder or not inorder: return None
root = TreeNode(preorder[0])
rootid = inorder.index(root.val)
# 要记得把递归的结果赋值给root.left和root.right
root.left = self.buildTree(preorder[1:rootid+1],inorder[:rootid])
root.right = self.buildTree(preorder[rootid+1:],inorder[rootid+1:])
return root