[leetcode] 1008. Construct Binary Search Tree from Preorder Traversal

Description

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.)

It’s guaranteed that for the given test cases there is always possible to find a binary search tree with the given requirements.

Example 1:

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

Constraints:

  • 1 <= preorder.length <= 100
  • 1 <= preorder[i] <= 10^8
  • The values of preorder are distinct.

分析

题目的意思是:根据二叉搜索树的前序遍历构建二叉搜索树,如果用递归的方法的话就需要找到当前的根结点以及左右分支就行了,根结点当然就是数组的第一个结点,做分支所有的数都比根结点小,右分支所有的数都比根结点大,所以遍历一下数组判断一下就行了哈。也可以根据二叉排序树的性质直接构建二叉搜索树,这样就不用找左右子树了,哈哈,这种方法好像走了捷径。

代码

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def create_tree(self,preorder):
        if(preorder==[]):
            return None
        root=TreeNode(preorder[0])
        idx=len(preorder)
        for i in range(1,len(preorder)):
            if(preorder[i]>root.val):
                idx=i
                break
        root.left=self.create_tree(preorder[1:idx])
        root.right=self.create_tree(preorder[idx:])
        return root
    def bstFromPreorder(self, preorder: List[int]) -> TreeNode:
        return self.create_tree(preorder)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值