# LeetCode 173. Binary Search Tree Iterator

121人阅读 评论(0)

## 原题要求

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 = new Stack<TreeNode>();

public BSTIterator(TreeNode root) {
TreeNode temp = root;
while (null != temp) {
stack.push(temp);
temp = temp.left;
}
}

/** @return whether we have a next smallest number */
public boolean hasNext() {
if (!stack.empty()) {
return true;
}
return false;
}

/** @return the next smallest number */
public int next() {
TreeNode temp = stack.pop();
if (null != temp.right) {
TreeNode newTemp = temp.right;
while (null != newTemp) {
stack.push(newTemp);
newTemp = newTemp.left;
}
}
return temp.val;
}
}


## 结束语

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：99288次
• 积分：2705
• 等级：
• 排名：第13821名
• 原创：178篇
• 转载：21篇
• 译文：0篇
• 评论：9条
文章分类
阅读排行
评论排行
最新评论