Binary Search Tree Iterator
2016-06-12 13:11
190 查看
自己能不能不要总犯下面那种那么2的错误。。
嫩不能尽量明白,自己写的每段code是做啥的,能负责任!!!
/**
* 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<>();
TreeNode node = root;
while (node != null) {
stack.push(node);
node = node.left;
}
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
//return stack.isEmpty();
return !stack.isEmpty();
}
/** @return the next smallest number */
public int next() {
TreeNode smallest = stack.pop();
if (smallest.right != null) {
TreeNode node = smallest.right;
while (node != null) {
stack.push(node);
node = node.left;
}
}
return smallest.val;
}
}
/**
* Your BSTIterator will be called like this:
* BSTIterator i = new BSTIterator(root);
* while (i.hasNext()) v[f()] = i.next();
*/
嫩不能尽量明白,自己写的每段code是做啥的,能负责任!!!
/**
* 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<>();
TreeNode node = root;
while (node != null) {
stack.push(node);
node = node.left;
}
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
//return stack.isEmpty();
return !stack.isEmpty();
}
/** @return the next smallest number */
public int next() {
TreeNode smallest = stack.pop();
if (smallest.right != null) {
TreeNode node = smallest.right;
while (node != null) {
stack.push(node);
node = node.left;
}
}
return smallest.val;
}
}
/**
* Your BSTIterator will be called like this:
* BSTIterator i = new BSTIterator(root);
* while (i.hasNext()) v[f()] = i.next();
*/
相关文章推荐
- poj2186 Popular Cows 题解——S.B.S.
- 进度条--第十五周
- C语言程序可以没有main函数
- QT 学习记录:渐变-QLinearGradient,QRadialGradient,QConicalGradient)
- Oracle 的安装与配置
- C# 位域[flags]
- AcceptEx WSAAccept accept
- python列表详解
- UVa 12118 nspector's Dilemma (构造+DFS+欧拉回路)
- Warning: Attempt to present A on B whose view is not in the window hierarchy!
- linux中断简介
- poj 1179 Polygon(化环为直+区间dp)
- 《软件工程》第十五周学习进度
- Android病毒查杀原理
- 欢迎使用CSDN-markdown编辑器
- 一些常用快捷键
- CentOS7 配置防火墙开放80端口
- Android ListView自适应高度和ScrollView冲突解决 [有效]
- 赞赏出版模式:在大众之中寻找大家,在凡品之上打造精品-百道网
- A. Round House