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 {private int idx;private List<Integer> arr;public BSTIterator(TreeNode root) {idx = 0;arr = new ArrayList<>();inorderTravel(root,arr);}public int next() {return arr.get(idx++);}public boolean hasNext() {return idx < arr.size();}//中序遍历public void inorderTravel(TreeNode root,List<Integer> arr){if(root == null){return;}inorderTravel(root.left,arr);arr.add(root.val);inorderTravel(root.right,arr);}
}/*** 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();*/