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

python

这里使用了 list.index(), 这个非常有用

# 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, inorder, postorder):
        """
        :type inorder: List[int]
        :type postorder: List[int]
        :rtype: TreeNode
        """
        # guard
        if len(inorder) ==0:
            return None
        
        root = TreeNode(postorder.pop(-1))
        
        if len(postorder)>0:
            left_in = inorder[:inorder.index(root.val)]
            right_in = inorder[inorder.index(root.val)+1:]
            if(len(left_in)>0):
                left_post = postorder[:len(left_in)]
                root.left = self.buildTree(left_in,left_post)
            if(len(right_in)>0):
                right_post = postorder[len(left_in):]
                root.right = self.buildTree(right_in, right_post)
        
        return root
        
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 根据一棵树的中序遍历与后序遍历构造二叉树。注意:你可以假设树中没有重复的元素。 例如 代码
    vbuer阅读 266评论 0 0
  • 一、Python简介和环境搭建以及pip的安装 4课时实验课主要内容 【Python简介】: Python 是一个...
    _小老虎_阅读 5,848评论 0 10
  • http://python.jobbole.com/85231/ 关于专业技能写完项目接着写写一名3年工作经验的J...
    燕京博士阅读 7,638评论 1 118
  • 又让我经历一次永远的痛,崩溃的边缘,身边的人都受折磨,我好无助
    静默修心阅读 147评论 0 0
  • 星期天,我的妈妈在洗衣服,我在旁边观察着妈妈洗衣服,妈妈先把衣服和洗衣液放进洗衣机里,接着把按钮摁下来,最后等着衣...
    小y_e652阅读 143评论 0 1