您的位置:首页 > 其它

[LeetCode]173 Binary Search Tree Iterator

2015-01-14 14:33 411 查看
https://oj.leetcode.com/problems/binary-search-tree-iterator/
/**
* Definition for binary tree
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/

public class BSTIterator {

//
// NOTE
// After the iterator built, if we modify the original tree,
// Ideally we should throw ConcurrentModificationException
// But this need some special logic when modify tree.
//
// In this case, we just make assumption that
// The iterator won't be effected after being built.

public BSTIterator(TreeNode root) {

// Validate
stack = new Stack<>();
pushAllLefts(root);
}

/** @return whether we have a next smallest number */
// O(1) time
// O(h) space
public boolean hasNext() {
return !stack.empty();
}

/** @return the next smallest number */
// O(h) time
// O(h) space
public int next() {

// Assume hasNext() == true.
//
// A Inorder visiting

TreeNode min = stack.pop();

// Can be done async
pushAllLefts(min.right);

return min.val;
}

private void pushAllLefts(TreeNode node)
{
while (node != null)
{
stack.push(node);
node = node.left;
}
}

private Stack<TreeNode> stack;
}

/**
* Your BSTIterator will be called like this:
* BSTIterator i = new BSTIterator(root);
* while (i.hasNext()) v[f()] = i.next();
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode