[LeetCode]173. 二叉搜索树迭代器(java实现)二叉树的中序遍历迭代算法
1. 题目
2. 读题(需要重点注意的东西)
思路(二叉树的中序遍历迭代算法):
即将中序遍历树的迭代算法拆分到三个函数中。
具体思路请见[LeetCode]94. 二叉树的中序遍历(java实现)二叉树遍历模板题,在此不再赘述。
3. 解法
---------------------------------------------------解法---------------------------------------------------
/**
* 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> stk = new Stack<>();
public BSTIterator(TreeNode root) {
while(root != null){
stk.push(root);
root = root.left;
}
}
public int next() {
TreeNode p = stk.pop();
int res = p.val;
p = p.right;
while(p != null){
stk.push(p);
p = p.left;
}
return res;
}
public boolean hasNext() {
return !stk.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();
*/
可能存在的问题: