# LeetCode 173. Binary Search Tree Iterator

154 篇文章 0 订阅
8 篇文章 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
收藏
觉得还不错? 一键收藏
• 打赏
• 0
评论

_海阔天空

¥1 ¥2 ¥4 ¥6 ¥10 ¥20

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、付费专栏及课程。