[Locked] Verify Preorder Sequence in Binary Search Tree
2016-02-23 22:16
585 查看
Verify Preorder Sequence in Binary Search Tree
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?
分析:
举个例子,5 2 1 3 4 7 6 8。前序遍历,访问顺序是:parent --> left --> right;而要保证这是一个二分搜索树,那么这棵树的每个子树节点从小到大顺序是:left < parent < right;我们发现一旦n(i+1)比n(i)大,那么它必定是之前某个parent的right child,则可以将该parent代表子树用right child压缩表示,即right child取代parent及其left child子树成为新的子树根节点。如果之后来了一个新节点值还比被取代的parent值小的话,return false;如果处理完所有的数,则return true。
解法一:
如果不考虑O(1)空间复杂度这个条件的话,用stack可实现压缩临近节点的步骤;
代码一:
解法二:
如果考虑O(1)空间复杂度这个条件,用递归其实不能算是O(1)空间复杂度的,我们可以修改解法一,用原数组来实现stack;
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?
分析:
举个例子,5 2 1 3 4 7 6 8。前序遍历,访问顺序是:parent --> left --> right;而要保证这是一个二分搜索树,那么这棵树的每个子树节点从小到大顺序是:left < parent < right;我们发现一旦n(i+1)比n(i)大,那么它必定是之前某个parent的right child,则可以将该parent代表子树用right child压缩表示,即right child取代parent及其left child子树成为新的子树根节点。如果之后来了一个新节点值还比被取代的parent值小的话,return false;如果处理完所有的数,则return true。
解法一:
如果不考虑O(1)空间复杂度这个条件的话,用stack可实现压缩临近节点的步骤;
代码一:
bool preorder(vector<int> nums) { stack<int> stk; int curp = INT_MIN; if(nums.empty()) return true; stk.push(nums[0]); for(int i = 1; i < nums.size(); i++) { if(nums[i] < curp) return false; while(!stk.empty() && stk.top() < nums[i]) { curp = stk.top(); stk.pop(); } stk.push(nums[i]); } return true; }
解法二:
如果考虑O(1)空间复杂度这个条件,用递归其实不能算是O(1)空间复杂度的,我们可以修改解法一,用原数组来实现stack;
相关文章推荐
- 使用phantomjs进行无界面UI自动化测试
- sequence有关问题
- hdu3530Subsequence【单调队列优化dp】2010多校联合
- 334. Increasing Triplet Subsequence【M】【69】
- STL_queue
- ios不同版本下的UILabel自动换行问题
- STL_deque
- 1101. Quick Sort (25)
- UITableViewControl的编辑(删除,添加,移动)
- IOS-53-图片、button等空间是否可拉伸设置;以及UITabelView的headerView设置
- 等待控件(UIActivityIndicatorView)不转动的原因
- Universal-Image-Loader(UIL)图片加载框架使用简单介绍
- IOS-52-UITableView中cell分割线左对齐(解决iOS8版本适配问题)
- Rocky's Requirements for ideal HW
- hdu 5288 OO’s Sequence
- Implement Stack using Queues
- 4.UIViewController
- iOS涂鸦画板 主要自定义UIView
- unable to find valid certification path to requested target或Certificate chaining error的解决办法
- uibutton点击按钮时title变大 松开时变小