Binary Search Tree Iterator
2016-07-09 23:01
344 查看
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class BSTIterator { Stack<TreeNode> stack; public BSTIterator(TreeNode root) { stack = new Stack<>(); while (root != null) { stack.push(root); root = root.left; } } /** @return whether we have a next smallest number */ public boolean hasNext() { return !stack.isEmpty(); } /** @return the next smallest number */ public int next() { TreeNode smallest = stack.pop(); if (smallest.right != null) { TreeNode right = smallest.right; while (right != null) { stack.push(right); right = right.left; } } return smallest.val; } } /** * Your BSTIterator will be called like this: * BSTIterator i = new BSTIterator(root); * while (i.hasNext()) v[f()] = i.next(); */
相关文章推荐
- Tyvj P1427 小白逛公园
- Handler消息传递机制
- 数据库基础
- hdu 5063(思路题-反向操作数组)
- asp.net用input控件上传文件时Check错误文件路径的方法
- 2016腾讯IEG实习面试
- 利用嵌套循环计算1到100的阶乘和
- 16、利用maven发布web项目到jetty
- VS中代码覆盖问题
- IOS 视频分解图片、图片合成视频
- ListCtrl的扩展类EditListCtrl
- JavaScript 中的 call() 和 apply() 方法深入理解
- RCNN + SPP + FAST RCNN + FASTER RCNN+ YOLO 论文总结
- 笨办法学Python之PowerShell入门篇
- 303. Range Sum Query - Immutable
- bootstrap3学习1:响应式布局layout
- springmvc配置日期转化
- 所有事件event集锦
- LinkedList 浅析示例
- linux wget