1. 程式人生 > >【leetcode】1008. Construct Binary Search Tree from Preorder Traversal

【leetcode】1008. Construct Binary Search Tree from Preorder Traversal

ever -o set 操作 strong and first upload pan

題目如下:

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

Example 1:

Input: [8,5,1,7,10,12]
Output: [8,5,10,1,7,null,12]
技術分享圖片

Note:

  1. 1 <= preorder.length <= 100
  2. 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

【leetcode】1008. Construct Binary Search Tree from Preorder Traversal