• [Leetcode]@python 106. Construct Binary Tree from Inorder and Postorder Traversal


    题目链接

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

    题目原文

    Given inorder and postorder traversal of a tree, construct the binary tree.

    题目大意

    根据中序遍历和后序遍历构建二叉树

    解题思路

    假设后序串:AEFDHZMG,后序的最后一个节点一定是根节点,这样我们就知道了根节点是G. 再看中序ADEFGHMZ, 在中序串之中,根结点的前边的所有节点都是左子树中,所以G节点前面的ADEF就是左子树的中序串。再看后序串 AEFDHZMG, 由于左子树的节点是ADEF,我们可以得到左子树的后序串为: AEFD. 有了左子树的后序串AEFD,和中序串ADEF ,我们就可以递归的把左子树给建立起来。 同样,可以建立起右子树。(但是这里要先构建右子树,再构建左子树,至于原因为啥,我还不造)

    代码

    # 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
            """
            if not inorder:
                return None
    
            index = inorder.index(postorder.pop())
            root = TreeNode(inorder[index])
    
            root.right = self.buildTree(inorder[index + 1:len(inorder)], postorder)
            root.left = self.buildTree(inorder[0:index], postorder)
            
            return root  
    
  • 相关阅读:
    spark java wordCount实例
    SpringMVC 商城项目
    jstl 遍历数据
    jquery 方法总结
    8ch
    7ch
    使用vuex实现组件间传值
    Vue父子组件之间传值
    从浏览器输入URL地址到最终页面渲染完成,发生了什么?
    数组去重
  • 原文地址:https://www.cnblogs.com/slurm/p/5262639.html
Copyright © 2020-2023  润新知