• 【leetcode】1008. Construct Binary Search Tree from Preorder Traversal


    题目如下:

    Return the root node of a binary search tree that matches the given preorder traversal.

    (Recall that a binary search tree is a binary tree where for every node, any descendant of node.left has a value < node.val, and any descendant of node.right has a value > node.val.  Also recall that a preorder traversal displays the value of the node first, then traverses node.left, then traverses node.right.)

    Example 1:

    Input: [8,5,1,7,10,12]
    Output: [8,5,10,1,7,null,12]
    
    

    Note: 

    1. 1 <= preorder.length <= 100
    2. The values of preorder are distinct.

    解题思路:以用例的输入[8,5,1,7,10,12]为例,很显然8是根节点,8的左子树有[5,1,7],右子树右[10,12],左右子树的分割点是后面第一个比根节点大的数。接下来再分别对[5,1,7]和[10,12]做同样的操作,可以知道5是8的左子树根节点,1和7分别在其左右;而10是8的右子树根节点,12为右子树节点。很显然这是一个递归的过程,只要找到每个子树的根节点将其左右子树划分即可。

    代码如下:

    # 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 build(self,node,preorder):
            if len(preorder) == 0:
                return
            left = []
            for i in range(len(preorder)):
                if node.val < preorder[i]:
                    break
                else:
                    left.append(preorder[i])
            right = preorder[len(left):]
            if len(left) >= 1:
                node.left = TreeNode(left.pop(0))
                self.build(node.left,left)
            if len(right) >= 1:
                node.right = TreeNode(right.pop(0))
                self.build(node.right,right)
        def bstFromPreorder(self, preorder):
            """
            :type preorder: List[int]
            :rtype: TreeNode
            """
            root = TreeNode(preorder.pop(0))
            self.build(root,preorder)
            return root
  • 相关阅读:
    nginx源码分析:module机制
    Linux源码分析之:malloc、free
    shell格式化字符串
    shell执行字符串中的命令
    docker安装并运行mongo
    docker安装并运行kibana
    docker安装并运行elasticsearch
    docker安装并运行rabbitmq
    docker安装并运行ngnix
    docker安装并运行redis
  • 原文地址:https://www.cnblogs.com/seyjs/p/10534110.html
Copyright © 2020-2023  润新知