From 6daa16d6d3377dfc5f2ae10da1a796b3828b45f3 Mon Sep 17 00:00:00 2001 From: KEQI HUANG Date: Fri, 29 Dec 2017 17:48:52 -0600 Subject: [PATCH] Update 255._Verify_Preorder_Sequence_in_Binary_Search_Tree.md --- ...Preorder_Sequence_in_Binary_Search_Tree.md | 31 +++++++++++++++++-- 1 file changed, 28 insertions(+), 3 deletions(-) diff --git a/255._Verify_Preorder_Sequence_in_Binary_Search_Tree.md b/255._Verify_Preorder_Sequence_in_Binary_Search_Tree.md index dd02e42..04b0e9a 100644 --- a/255._Verify_Preorder_Sequence_in_Binary_Search_Tree.md +++ b/255._Verify_Preorder_Sequence_in_Binary_Search_Tree.md @@ -20,6 +20,8 @@ Medium 5 12 / \ 2 6 + + preorder:[10, 5, 2, 6, 12] ``` 如这个例子,我们在10的位置是没有最小值限定的,然后降序走到5,依然没有最小值,降序走到2,依然没有,然后开始升序了,遇到6,这时候之后的数字一定大于2,同时也大于5,所以最小值更新为之前遍历过的,且比当前数稍微小一点的那个数。这里我们可以用一个栈来暂存之前的路径,所以升序时就是将栈中元素不断pop出来直到栈顶大于当前数,而最小值就是最后一个pop出来的数,最后再把该数push进去。对于降序的时候,直接向里面push就行了。这样,序列无效的条件就是违反了这个最小值的限定。 @@ -34,12 +36,35 @@ class Solution(object): :rtype: bool """ stack = [] - lower = -1 << 31 # 初始化最小值为最小整数 + min_num = -1 << 31 # 初始化最小值为最小整数 for x in preorder: - if x < lower: # 违反最小值限定则是无效的 + if x < min_num: # 违反最小值限定则是无效的 return False while stack and x > stack[-1]: # 将路径中所有小于当前的数pop出来并更新最小值 - lower = stack.pop() + min_num = stack.pop() stack.append(x) # 将当前值push进去 return True ``` + +Follow up: O(1) space +we realize that the preorder array can be reused as the stack thus achieve O(1) extra space, since the scanned items of preorder array is always more than or equal to the length of the stack. +```python +class Solution(object): + def verifyPreorder(self, preorder): + """ + :type preorder: List[int] + :rtype: bool + """ + # stack = preorder[:i], reuse preorder as stack + lower = -1 << 31 + i = 0 + for x in preorder: + if x < lower: + return False + while i > 0 and x > preorder[i - 1]: + lower = preorder[i - 1] + i -= 1 + preorder[i] = x + i += 1 + return True +``` -- GitLab