zoukankan      html  css  js  c++  java
  • 【leetcode】106. Construct Binary Tree from Inorder and Postorder Traversal

    题目如下:

    解题思路:本题是根据中序和后序来构建树,和【leetcode】105. Construct Binary Tree from Preorder and Inorder Traversal思路一样。只不过后序遍历的结果是根节点在后,所以依次取根节点的方法就是postorder.pop(-1),因为倒着取的,所以遍历的时候,需要先右后左。

    代码如下:

    # 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 traverse(self,parent,postorder,inorder,director):
            if len(postorder) == 0 or len(inorder) == 0:
                return
            node = TreeNode(postorder.pop(-1))
            if director == 'L':
                parent.left = node
            else:
                parent.right = node
    
            inx = inorder.index(node.val)
            self.traverse(node, postorder, inorder[inx + 1:], 'R')
            self.traverse(node, postorder, inorder[0:inx], 'L')
    
        def buildTree(self, inorder, postorder):
            """
            :type inorder: List[int]
            :type postorder: List[int]
            :rtype: TreeNode
            """
            if len(postorder) == 0 or len(inorder) == 0:
                return None
            root = TreeNode(postorder.pop(-1))
            inx = inorder.index(root.val)
            self.traverse(root,postorder,inorder[inx+1:],'R')
            self.traverse(root, postorder, inorder[0:inx], 'L')
            return root
            
  • 相关阅读:
    CAP分布式
    专职DBA-MySQL数据库开篇
    os.sep
    DocStrings
    Python如何获取脚本的参数
    LVM基础命令
    VoAndEntityTrans
    短信倒计时
    springboot在eclipse上搭建项目一(无页面)
    springboot问题
  • 原文地址:https://www.cnblogs.com/seyjs/p/9660685.html
Copyright © 2011-2022 走看看