题目描述:
返回与给定先序遍历 preorder
相匹配的二叉搜索树(binary search tree)的根结点。
(回想一下,二叉搜索树是二叉树的一种,其每个节点都满足以下规则,对于 node.left
的任何后代,值总 <
node.val
,而 node.right
的任何后代,值总 >
node.val
。此外,先序遍历首先显示节点的值,然后遍历 node.left
,接着遍历 node.right
。)
示例:
提示:
1 <= preorder.length <= 100
preorder
中的值是不同的。# 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 bstFromPreorder(self, preorder):
"""
:type preorder: List[int]
:rtype: TreeNode
"""
#思路:对于二叉搜索树,其具有根节点的左子树所有节点值都小于根节点的值;根节点的右子树所有节点值都大于根节点的值
def pretree(root,left_,right_):
if len(left_) != 0:
root.left = TreeNode(left_[0])
left_i = []
right_i = []
for i in range(1,len(left_)):
if left_[i] < left_[0]:
left_i.append(left_[i])
if left_[i] > left_[0]:
right_i.append(left_[i])
pretree(root.left,left_i,right_i)
if len(right_) != 0:
root.right = TreeNode(right_[0])
left_j = []
right_j = []
for i in range(1,len(right_)):
if right_[i] < right_[0]:
left_j.append(right_[i])
if right_[i] > right_[0]:
right_j.append(right_[i])
pretree(root.right,left_j,right_j)
if preorder == None:
return TreeNode(None)
else:
root = TreeNode(preorder[0])
left = []
right = []
for i in range(1,len(preorder)):
if preorder[i] < preorder[0]:
left.append(preorder[i])
if preorder[i] > preorder[0]:
right.append(preorder[i])
pretree(root,left,right)
return root
菜鸟一枚,代码仅供参考,如有问题,望指正~