ð 173. äºåæ玢æ è¿ä»£åš
2022幎10æ10æ¥
- algorithm
ð 173. äºåæ玢æ è¿ä»£åš
éŸåºŠ: ð
é®é¢æè¿°
解æ³
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class BSTIterator {
// æè·¯ïŒ
// äžåºéå - è¿ä»£
TreeNode root;
LinkedList<TreeNode> stack;
public BSTIterator(TreeNode root) {
this.root = root;
this.stack = new LinkedList<>();
// å®äœå° next éŠèç¹
TreeNode cur = root;
if(!stack.isEmpty() || cur != null) {
while(cur != null) {
stack.push(cur);
cur = cur.left;
}
}
}
public int next() {
TreeNode cur = stack.pop();
int res = cur.val;
cur = cur.right;
if(!stack.isEmpty() || cur != null) {
while(cur != null) {
stack.push(cur);
cur = cur.left;
}
}
return res;
}
public boolean hasNext() {
return !stack.isEmpty();
}
}
/**
* Your BSTIterator object will be instantiated and called as such:
* BSTIterator obj = new BSTIterator(root);
* int param_1 = obj.next();
* boolean param_2 = obj.hasNext();
*/