zoukankan      html  css  js  c++  java
  • [LeetCode]题解(python):106-Construct Binary Tree from Inorder and Postorder Traversal

    题目来源:

      https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/


    题意分析:

      给出一颗二叉树的中序遍历和后续遍历,还原这个树。


    题目思路

      这题和上一题类似,用递归的思想,先根据后序遍历的最后一个确定根节点,然后将中序遍历分成两部分,接着递归就可以了。


    代码(python):

      

    # 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
            """
            def dfs(ibegin,iend,pbegin,pend):
                if pbegin >= pend:
                    return None
                if pbegin == pend - 1:
                    return TreeNode(postorder[pend - 1])
                i = inorder.index(postorder[pend - 1]) - ibegin
                ans = TreeNode(postorder[pend - 1])
                ans.left = dfs(ibegin,ibegin+i,pbegin,pbegin + i)
                ans.right = dfs(ibegin + 1 + i,iend,pbegin + i,pend - 1)
                return ans
            return dfs(0,len(inorder),0,len(postorder))
                
    View Code
  • 相关阅读:
    typescript-泛型-类型检查
    typescript-class-interface
    typescript-类class
    typescript-接口interface
    Oracle 密码过期
    VMware Redhat虚拟机扩容硬盘
    华硕 U系列电脑拆后盖注意事项
    VS + QT 出现 LNK2001 无法解析的外部符号 QMetaObject 的问题
    c++ _pFirstBlock == pHead
    c++ 套路多
  • 原文地址:https://www.cnblogs.com/chruny/p/5258231.html
Copyright © 2011-2022 走看看