您的位置:首页 > 其它

[LeetCode]173. Binary Search Tree Iterator

2016-03-02 21:11 369 查看

Problem Description

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.

思路

利用一个全局stack

Code

package q173;

import java.util.Stack;

import TreeNode.TreeNode;

public class BSTIterator {

private Stack<TreeNode> s=new Stack<TreeNode>();
private void PushAll(TreeNode root){
while(root!=null){
s.push(root);
root=root.left;
}
}
public BSTIterator(TreeNode root) {
PushAll(root);
}

/** @return whether we have a next smallest number */
public boolean hasNext() {
return !s.isEmpty();
}

/** @return the next smallest number */
public int next() {
TreeNode tmp=s.pop();
PushAll(tmp.right);
return tmp.val;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode