173. 二叉搜索树迭代器

从题意可以看出,实际上就是对二叉搜索树进行中序遍历,得到一个从小到大排序的序列,进行nexthasNext操作

本题中的中序遍历我用的是“颜色标记法”

/**
 * 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<>();
        arr = inorder(root);
    }
    
    public int next() {
        return arr.get(idx++);
    }
    
    public boolean hasNext() {
        // if (idx < arr.size()) return true;
        // else return false;
        return idx < arr.size();
    }

    private List<Integer> inorder(TreeNode root) {
        List<Integer> ans = new ArrayList<>();
        Stack<Object> st = new Stack<>();
        st.push(root);
        while (!st.isEmpty()) {
            Object o = st.pop();
            if (o instanceof TreeNode) {
                st.push(((TreeNode) o).right);
                st.push(((TreeNode) o).val);
                st.push(((TreeNode) o).left);
            } else if (o instanceof Integer) {
                ans.add((Integer) o);
            }
        }
        return ans;
    }
}

/**
 * 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();
 */

你可能感兴趣的:(LeetCode,数据结构,算法,java)