zoukankan      html  css  js  c++  java
  • Leetcode练习(Python):数组类:第106题:根据一棵树的中序遍历与后序遍历构造二叉树。 注意: 你可以假设树中没有重复的元素。

    题目:
    根据一棵树的中序遍历与后序遍历构造二叉树。  注意: 你可以假设树中没有重复的元素。
    思路:
    与第105题类似,区别是前序遍历一开始找的是左子树的结点,后续遍历一开始找的是右子树的结点,因为从后面开始找数字。
    程序:
    # Definition for a binary tree node.
    # class TreeNode:
    #     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
            """
            if not inorder or not postorder:
                return None
            tree_root = TreeNode(postorder.pop())
            tree_root_index = inorder.index(tree_root.val)
            tree_root.right = self.buildTree(inorder[tree_root_index + 1:], postorder)
            tree_root.left = self.buildTree(inorder[:tree_root_index], postorder)
            return tree_root
  • 相关阅读:
    明星球队的傲慢
    VS2010测试方面的文章重点
    项目管理有感
    团队从小到大,再到体验团队
    css实现文字渐变
    echarts坐标轴文字过长省略
    mustache+mock
    你有选择的权利
    呵呵,初学者小编
    Centos7升级到OpenSSH_8.8p1、OpenSSL 1.1.1l版本
  • 原文地址:https://www.cnblogs.com/zhuozige/p/12766966.html
Copyright © 2011-2022 走看看