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)