LeetCode 173. 【Java】173. Binary Search Tree Iterator
原题链接
中等
作者:
tt2767
,
2020-02-07 13:32:22
,
所有人可见
,
阅读 736
/*
1. 题目要求可以转换成将一个树的inorder 按从左到右的顺序输出
2. 开始读错题了,应该是next函数要O(1)的时间,O(h)空间, 所以可以预处理一下
3. 按照 迭代法 求中序遍历去做即可
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class BSTIterator {
Stack<TreeNode> stack;
public BSTIterator(TreeNode root) {
stack = new Stack<TreeNode>();
scanLeft(root);
}
private void scanLeft(TreeNode root){
while (root != null){
stack.push(root);
root = root.left;
}
}
/** @return the next smallest number */
public int next() {
var node = stack.pop();
scanLeft(node.right);
return node.val;
}
/** @return whether we have a next smallest number */
public boolean hasNext() {
return !stack.isEmpty();
}
}
/**
* Your BSTIterator object will be instantiated and called as such:
* BSTIterator obj = new BSTIterator(root);
* int param_1 = obj.next();
* boolean param_2 = obj.hasNext();
*/