LeetCode Verify Preorder Sequence in Binary Search Tree
2016-03-28 06:46
501 查看
原题链接在这里:https://leetcode.com/problems/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?
题解:
Method 1 利用stack模拟preorder. stack中放的是左子树. 遇到比stack top还要大, 说明遇到了以top 为root的右子树,把左子树连同root 都pop出来.
low是当前的lower bound, pop出来说明左边扫完了,不可能出现更小的了,所以更新low. 若是遇到比low还小就说明不是preorder.
Time Complexity: O(n). Space: O(logn).
Method 2 是在array本身上实现stack的功能.
Time Complexity: O(n). Space: O(1).
AC Java:
题目:
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?
题解:
Method 1 利用stack模拟preorder. stack中放的是左子树. 遇到比stack top还要大, 说明遇到了以top 为root的右子树,把左子树连同root 都pop出来.
low是当前的lower bound, pop出来说明左边扫完了,不可能出现更小的了,所以更新low. 若是遇到比low还小就说明不是preorder.
Time Complexity: O(n). Space: O(logn).
Method 2 是在array本身上实现stack的功能.
Time Complexity: O(n). Space: O(1).
AC Java:
public class Solution { public boolean verifyPreorder(int[] preorder) { /* //Method 1 int low = Integer.MIN_VALUE; Stack<Integer> stk = new Stack<Integer>(); for(int num : preorder){ if(num < low){ return false; } while(!stk.isEmpty() && stk.peek() < num){ low = stk.pop(); } stk.push(num); } return true; */ int index = -1; int low = Integer.MIN_VALUE; for(int num : preorder){ if(num < low){ return false; } while(index >= 0 && preorder[index] < num){ low = preorder[index--]; } preorder[++index] = num; } return true; } }
相关文章推荐
- [LeetCode] Verify Preorder Sequence in Binary Search Tree 验证二叉搜索树的先序序列
- 60. Permutation Sequence
- andorid UI事件 监听器
- andorid UI事件
- UITabBarController简单介绍
- UITableviewcell的性能问题
- UITableview控件简单介绍
- iOS控件--UILabel
- ZooKeeper Programmer's Guide(中文翻译)
- cf#316-codeforces570D - Tree Requests -dfs序+分类再二分+树dp+异或位运算+bitmask(位压缩)
- salesforce 零基础开发入门学习(七)PickList的value值获取
- 快速排序测试(QuickSort)
- 配置fluent将日志转储到elasticsearch
- UI控件--ViewPager详解四大函数(2)
- Android UI模板设计---TopBar(标题栏)
- Xming的一点tips
- Mysql slow query log
- iOS边练边学--Segue数据逆传(用block代替delegate)
- uestc1131男神的礼物【dp】
- Conditional jump or move depends on uninitialised value(s)-1