• [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
  • 相关阅读:
    Log4j2 配置
    Spring + SpringMVC配置
    Tomcat 动态数据库连接池
    MySQL数据库备份命令
    一条insert语句插入数据库
    tomcat 性能优化
    linux RPM manager
    mysql 多主
    ceph学习
    python常用程序算法
  • 原文地址:https://www.cnblogs.com/chruny/p/5258231.html
Copyright © 2020-2023  润新知