Leetcode Verify Preorder Sequence in Binary Search Tree
2015-10-22 03:15
441 查看
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?
Kinda simulate the traversal, keeping a stack of nodes (just their values) of which we're still in the left subtree. If the next number is smaller than the last stack value, then we're still in the left subtree of all stack nodes, so just push the new one onto the stack. But before that, pop all smaller ancestor values, as we must now be in their right subtrees (or even further, in the right subtree of an ancestor). Also, use the popped values as a lower bound, since being in their right subtree means we must never come across a smaller number anymore.
Java code:
Reference:
1. https://leetcode.com/discuss/51543/java-o-n-and-o-1-extra-space
You may assume each number in the sequence is unique.
Follow up:
Could you do it using only constant space complexity?
解题思路:
参考答案,记住!Kinda simulate the traversal, keeping a stack of nodes (just their values) of which we're still in the left subtree. If the next number is smaller than the last stack value, then we're still in the left subtree of all stack nodes, so just push the new one onto the stack. But before that, pop all smaller ancestor values, as we must now be in their right subtrees (or even further, in the right subtree of an ancestor). Also, use the popped values as a lower bound, since being in their right subtree means we must never come across a smaller number anymore.
Java code:
public class Solution { public boolean verifyPreorder(int[] preorder) { int low = Integer.MIN_VALUE; Stack<Integer> path = new Stack<Integer>(); for(int p: preorder){ if(p < low){ return false; } while(!path.isEmpty() && p > path.peek()){ low = path.pop(); } path.push(p); } return true; } }
Reference:
1. https://leetcode.com/discuss/51543/java-o-n-and-o-1-extra-space
相关文章推荐
- *LeetCode-Verify Preorder Sequence in Binary Search Tree
- Guess(精确2位浮点数)
- String StringBuilder StringBuffer 对比 总结得非常好
- UICollectionView创建实例
- 电子商务系统的设计与实现(七):前后端系统UI设计的一些思考
- UVA 1612 Guess
- UVA_1605: Building for UN
- CodeForces - 369E Valera and Queries(树状数组)
- IOS-UI控件大全
- 2015/10/21 UICollectionViewController 使用
- Under the Hood: Rebuilding Facebook for Android
- STL学习笔记-priority quene容器(优先级队列)
- STL学习笔记-quene容器(队列)
- STL学习笔记-deque容器(双端动态数组)
- DOTween 模仿NGUI Tween
- 【IOS 开发学习总结-OC-63】UIImage 与 CGImage,CGImageRef
- 黑马程序员--GUI
- String、StringBuffer和StringBuilder的异同和用法
- 【UIKit-106-1】UISwitch - 基础使用
- UVA-11324 The Largest Clique (强连通+DP)