/**
* 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 {
//栈用于迭代
Stack<TreeNode> stack;
TreeNode cur;
//记录当前节点
public BSTIterator(TreeNode root) {
//初始化两个值
stack = new Stack<TreeNode>();
cur = root;
}
public int next() {
//返回一个节点
while(cur != null){
stack.push(cur);
cur = cur.left;
}
cur = stack.pop();
int val = cur.val;
cur = cur.right;
return val;
}
public boolean hasNext() {
//判断当前是否还有节点可以迭代,就是判断栈中是否为空或者当前节点是否还能接着将节点加入栈
return !stack.isEmpty() || cur != null;
}
}
/**
* 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();
*/
二叉搜索树迭代器java实现
最新推荐文章于 2023-11-15 23:15:54 发布