题目如下:
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 ofnode.right
has a value>
node.val
. Also recall that a preorder traversal displays the value of thenode
first, then traversesnode.left
, then traversesnode.right
.)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.
解题思路:以用例的输入[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