LeetCode:Binary Search Tree Iterator
2016-06-01 16:18
405 查看
Binary Search Tree Iterator
Total Accepted: 49694 TotalSubmissions: 141917 Difficulty: Medium
Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.
Calling
next()will return the next smallest
number in the BST.
Note:
next()and
hasNext()should
run in average O(1) time and uses O(h) memory, where h is the height of the tree.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
Hide Tags
Tree Stack Design
Hide Similar Problems
(M) Binary Tree Inorder Traversal (M)
Flatten 2D Vector (M) Zigzag Iterator (M)
Peeking Iterator (M) Inorder Successor in BST
思路:
设有BST:
4
2 7
0 3 5 8
将root的所有“左”孩子入栈stack(4->2->0)
next()方法:
0(栈顶,下同):由于0没有右孩子,无操作,这时stack(4->2);
2:2有右孩子3,将3的“左”孩子入栈,这里stack(4->3);
3:stack(4);
4:stack(7->5)
5:stack(7)
7:stack(8)
8:stack(null)
hasNext()方法:判断stack是否为空即可;
java code:
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class BSTIterator {
private Stack<TreeNode> stack = new Stack<TreeNode>();
public BSTIterator(TreeNode root) {
pushLeft(root);
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
return !stack.isEmpty();
}
/** @return the next smallest number */
public int next() {
TreeNode tmp = stack.pop();
pushLeft(tmp.right);
return tmp.val;
}
// 自定义函数:将“左”孩子入栈
public void pushLeft(TreeNode root) {
while(root != null) {
stack.push(root);
root = root.left;
}
}
}
/**
* Your BSTIterator will be called like this:
* BSTIterator i = new BSTIterator(root);
* while (i.hasNext()) v[f()] = i.next();
*/
相关文章推荐
- Java4Android第11课:内部类和匿名内部类
- Android Application的理解和使用
- 状态栏字体颜色控制
- windows下 PyCharm安装scrapy
- Java Collections Framework Java集合框架概览
- 4.1.按键--按下按键使LED点亮
- 《图解TCP/IP》读书笔记(5)
- ie下不打开控制台js无法执行
- 初识java.util.concurrent.CountDownLatch
- 欢迎使用CSDN-markdown编辑器
- 数据结构_P10
- 12 打印1到最大的N位数(递归和非递归解法)
- Swift开篇009->方法
- 删除字符串中的指定字符(23)
- 在jdbc中使用properites文件进行使用
- Oracle数据库DOC命令导入导出(2014-3-10记)
- 通过http流发送post请求
- 练习2.21 2.23
- 88----oracle大对象,boolean,date的处理
- 1025. 反转链表 (25)