剑指 Offer II 055. 二叉搜索树迭代器
解题思路
1.将二叉树转换为链表
2.内部维护currentindex与list,来获取next和判断是否已经遍历到尾端
解题遇到的问题
无
后续需要总结学习的知识点
源码的遍历如何实现的?
##解法1
import java.util.ArrayList;
import java.util.List;
class BSTIterator {
List<Integer> listvalue = null;
int currentIndex = 0;
public BSTIterator(TreeNode root) {
listvalue = new ArrayList<>();
addList(root);
currentIndex = 0;
}
public int next() {
return listvalue.get(currentIndex++);
}
public void addList(TreeNode node) {
if (node == null) {
return;
}
addList(node.left);
listvalue.add(node.val);
addList(node.right);
}
public boolean hasNext() {
return currentIndex < listvalue.size();
}
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;
}
}
}