標籤:src binary lis bool 大於 app tor tco array
驗證一個list是不是一個BST的preorder traversal sequence。
Given an array of numbers, verify whether it is the correct preorder traversal sequence of a binary search tree.
You may assume each number in the sequence is unique.
Follow up:
Could you do it using only constant space complexity?
觀察這個例子: [8, 3, 1, 6, 4, 7, 10, 14, 13],
8, 3, 1 這三個連續遞減的數說明從root開始我們一直在往左邊走,直到出現6。
6應該是3的right child,因為他比3大,但是比8小。這時min這個指標應該等於3。也就是說之後list中的所有數都不能小於3。因為6是3的right child,說明3的本身和他的左子樹已經遍曆完畢,之後的所有數都應該比3大。
然後又是下降,直到出現7。這時應該將min更新為6。之後所有的數都應該大於6。以此類推。我們要做的是維護一個stack。如果elem < min, return False。如果elem < stack[-1], 把elem push進stack。如果elem > stack[-1], 那麼pop出stack中比elem小的那些數字,並更新min。具體的步驟看:
min = -MaxInt
8,
8, 3,
8, 3, 1
8, 6 min = 3
8, 6, 4,
8, 7 min = 6
10, min = 8
14, min = 10
14, 13
1 class Solution(object): 2 def verifyPreorder(self, preorder): 3 """ 4 :type preorder: List[int] 5 :rtype: bool 6 """ 7 stack = [] 8 min = -0x7FFFFFFF 9 for elem in preorder:10 if elem < min:11 return False12 while stack and stack[-1] < elem:13 min = stack.pop()14 stack.append(elem)15 return True
Follow Up: 如何驗證postorder和midorder?
A: 中序排列是遞增數列。
postorder的順序是left-right-root,那麼這個例子應該是[1, 4, 7, 6, 3, 13, 14, 10, 8]
比較容易的方式是從root開始驗證,由於後續root再後面,我們可以先把list reverse一下。然後思路和上面差不多,只不過要遞減改為遞增。記錄min改成記錄max。
Leetcode 255. Verify Preorder Sequence in Binary Search Tree