【leetcode 105】从前序与中序遍历序列构造二叉树

最后将构造好的树的根节点返回即可,利用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
上一篇:2021-02-02 已知二叉树的前序遍历和中序遍历求二叉树


下一篇:LeetCode | 0230. 二叉搜索树中第K小的元素【Python】