您的位置:首页 > 其它

Binary Search Tree Iterator

2016-06-04 16:43 225 查看
题目描述:

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.

题目意思是设计一个迭代器,每次得到容器内最小的值。

一直往左子树走,就是最小值,然后看这个最小值有没有又子树且这个右子树之前没有被访问过,如果有右子树就接着往右子树的左子树走,没有的话弹出来看这个节点的父节点。

代码如下:

public class BSTIterator {

Stack<TreeNode> stack;
Set<TreeNode> visited;

public BSTIterator(TreeNode root) {
stack=new Stack<TreeNode>();
visited=new HashSet<TreeNode>();
stack.add(root);
}

/** @return whether we have a next smallest number */
public boolean hasNext() {
if(!stack.isEmpty()){
return stack.peek()==null?false:true;
}
return false;
}

public int next() {
TreeNode node=stack.peek();
while(node.left!=null&&!visited.contains(node.left)){
stack.add(node.left);
node=node.left;
}
node=stack.pop();
if(node.right!=null&&!visited.contains(node.right))
stack.add(node.right);
visited.add(node);
return node.val;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: