2 Star 10 Fork 2

CG国斌 / myleetcode

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
_173.java 1.76 KB
一键复制 编辑 原始数据 按行查看 历史
Charies Gavin 提交于 2020-02-06 12:44 . 初始化 myleetcode 项目
package com.hit.basmath.learn.binary_search_tree;
import com.hit.common.TreeNode;
import java.util.Stack;
/**
* 173. Binary Search Tree Iterator
* <p>
* Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.
* <p>
* Calling next() will return the next smallest number in the BST.
* <p>
* Example:
* <p>
* BSTIterator iterator = new BSTIterator(root);
* iterator.next(); // return 3
* iterator.next(); // return 7
* iterator.hasNext(); // return true
* iterator.next(); // return 9
* iterator.hasNext(); // return true
* iterator.next(); // return 15
* iterator.hasNext(); // return true
* iterator.next(); // return 20
* iterator.hasNext(); // return false
* <p>
* Note:
* <p>
* 1. next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.
* 2. You may assume that next() call will always be valid, that is, there will be at least a next smallest number in the BST when next() is called.
*/
public class _173 {
class BSTIterator {
private Stack<TreeNode> stack = new Stack<TreeNode>();
public BSTIterator(TreeNode root) {
pushAll(root);
}
/**
* @return whether we have a next smallest number
*/
public boolean hasNext() {
return !stack.isEmpty();
}
/**
* @return the next smallest number
*/
public int next() {
TreeNode tmpNode = stack.pop();
pushAll(tmpNode.right);
return tmpNode.val;
}
private void pushAll(TreeNode node) {
while (node != null) {
stack.push(node);
node = node.left;
}
}
}
}
Java
1
https://gitee.com/guobinhit/myleetcode.git
git@gitee.com:guobinhit/myleetcode.git
guobinhit
myleetcode
myleetcode
master

搜索帮助