栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

[leetcode]106.从中序与后序遍历序列构造二叉树

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

[leetcode]106.从中序与后序遍历序列构造二叉树

根据一棵树的中序遍历与后序遍历构造二叉树。

注意:
你可以假设树中没有重复的元素。

例如,给出

中序遍历 inorder = [9,3,15,20,7]
后序遍历 postorder = [9,15,7,20,3]

返回如下的二叉树:

    3
   / 
  9  20
    /  
   15   7
class Solution:
    def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode:
        n = len(inorder)
        m = len(postorder)
        if m != n:
            return None
        mapper = {}
        for index,num in enumerate(inorder):
            mapper[num] = index
        return self.build(postorder,0,n-1,mapper,0,m-1)
    def build(self,postorder,postLeft,postRight,mapper,inLeft,inRight):
        if postLeft>postRight or inLeft>inRight:
            return None
        root_val = postorder[postRight]
        root = TreeNode(root_val,None,None)
        index = mapper.get(root_val)
        root.left = self.build(postorder,postLeft,postRight-inRight+index-1,mapper,inLeft,index-1)
        root.right = self.build(postorder,postRight-inRight+index,postRight-1,mapper,index+1,inRight)
        return root

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/276101.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号