美文网首页
python实现leetcode之105. 从前序与中序遍历序列

python实现leetcode之105. 从前序与中序遍历序列

作者: 深圳都这么冷 | 来源:发表于2021-09-26 00:11 被阅读0次

解题思路

前序的第一个元素就是root节点的值
然后这个元素将中序遍历的数组一分为二,左边为左子树,右边为右子树
前序遍历和中序遍历长度是一样的,所以从前序遍历切左子树长度的数组,就是左子树的前序遍历,右子树类似
然后递归处理左右子树即可

105. 从前序与中序遍历序列构造二叉树

代码

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def buildTree(self, preorder, inorder):
        """
        :type preorder: List[int]
        :type inorder: List[int]
        :rtype: TreeNode
        """
        if not preorder:
            return None
        root_val = preorder[0]
        idx = inorder.index(root_val)
        root = TreeNode(root_val)
        root.left = self.buildTree(preorder[1:idx+1], inorder[0:idx])
        root.right = self.buildTree(preorder[idx+1:], inorder[idx+1:])
        return root
效果图

相关文章

网友评论

      本文标题:python实现leetcode之105. 从前序与中序遍历序列

      本文链接:https://www.haomeiwen.com/subject/eisfnltx.html