/*
* 255. Verify Preorder Sequence in Binary Search Tree
Total Accepted: 8634 Total Submissions: 23097 Difficulty: Medium
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?
Hide Company Tags Zenefits
Hide Tags Tree Stack
Hide Similar Problems (M) Binary Tree Preorder Traversal
*/
package tree;
import java.util.Stack;
public class VerifyPreOrderBST {
public boolean verifyPreorder(int[] preorder) {
// store the nodes using a stack path. if path.isEmpty() or p < path.peek(), we still in the left subtree, just push p into path; if p > path.peek(), we pop the node as a low bound, push p into path. For the next p if smaller than low bound. return false, since being in their right subtree means we must never come across a smaller number anymore.
// https://leetcode.com/discuss/51543/java-o-n-and-o-1-extra-space
// test case : [4, 2, 1, 3, 6, 8,5] => false
if (preorder == null || preorder.length == 0) {
return true;
}
int low = Integer.MIN_VALUE;
Stack<Integer> path = new Stack<>();
for (int p : preorder) {
if (p < low) {
return false;
}
while (!path.isEmpty() && p > path.peek()) {
low = path.pop();
}
path.push(p);
}
return true;
}
}
255. Verify Preorder Sequence in Binary Search Tre
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- Given an array of numbers, verify whether it is the corre...
- Given an array of numbers, verify whether it is the corre...
- 解題思路 : recursive 作業順序: 往左檢查 left child 只要有符合 > k1 的 node ...
- Search Range in Binary Search Tree 今天是一道有关二叉树的题目,来自LintCo...