zoukankan      html  css  js  c++  java
  • [Leetcode]@python 105. Construct Binary Tree from Preorder and Inorder Traversal

    题目链接

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

    题目原文

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

    题目大意

    给定二叉树的先序和中序排列,构建二叉树

    解题思路

    假设先序串:DBACEGF,先序的第一个节点一定是根节点,这样我们就知道了根节点是D. 再看中序ABCDEFG, 在中序串之中,根结点的前边的所有节点都是左子树中,所以D节点前面的ABC就是左子树的中序串。再看先序串 DBACEGF, 由于左子树的节点是ABC,我们可以得到左子树的先序串为: BAC. 有了左子树的先序串BAC,和中序串ABC ,我们就可以递归的把左子树给建立起来。 同样,可以建立起右子树。

    代码

    # 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, preorder, inorder):
            """
            :type preorder: List[int]
            :type inorder: List[int]
            :rtype: TreeNode
            """
            if not inorder:
                return None
            else:
                index = inorder.index(preorder.pop(0))
                root = TreeNode(inorder[index])
                root.left = self.buildTree(preorder, inorder[0:index])
                root.right = self.buildTree(preorder, inorder[index + 1:])
                return root    
    
  • 相关阅读:
    test example
    SSD: ReLU6
    jupyter
    ubuntu+anaconda
    linux动态库
    ssd制作数据和训练
    ncnn框架
    Lock->ReentrantLock->ReentrantReadWriteLock简介
    Synchronized简介与原理
    ThreadLocal简介与原理
  • 原文地址:https://www.cnblogs.com/slurm/p/5240039.html
Copyright © 2011-2022 走看看