本文主要是介绍二叉搜索树迭代器java实现,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
/**
* 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实现的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!