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
.)
返回与给定先序遍历 preorder
相匹配的二叉搜索树(binary search tree)的根结点。
(回想一下,二叉搜索树是二叉树的一种,其每个节点都满足以下规则,对于 node.left
的任何后代,值总 < node.val
,而 node.right
的任何后代,值总 > node.val
。此外,先序遍历首先显示节点的值,然后遍历 node.left
,接着遍历 node.right
。)
题目链接:https://leetcode.com/problems/construct-binary-search-tree-from-preorder-traversal/
Difficulty: medium
Example 1:
Input: [8,5,1,7,10,12]
Output: [8,5,10,1,7,null,12]
Note:
- 1 <= preorder.length <= 100
- The values of preorder are distinct.
分析
- 前序遍历的规则是根左右,二叉搜索树满足同时根节点大于左子树的所有节点,小于右子树的所有节点;
- 定义递归过程,若当前遍历序列为空,返回None;
- 反之,以遍历序列第一个节点作为根节点root,小于根节点的序列作为左子树,大于根节点的序列作为右子树,形如[tar,l1,l2,l3,l4,r1,r2,r3,r4,r5];
- 调用自身构造左子树、右子树,与根节点连接,返回根节点。
参考代码
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):
if(len(preorder)==0):
return None
root=TreeNode(preorder[0])
le=[]
ri=[]
for i in range(1,len(preorder)):
if(preorder[i]<preorder[0]):
le.append(preorder[i])
else:
ri.append(preorder[i])
left=self.bstFromPreorder(le)
right=self.bstFromPreorder(ri)
root.left=left
root.right=right
return root