二叉树迭代器设计

题目描述

173. 二叉搜索树迭代器

题解

思路一:扁平化

事先生成二叉树的中序遍历序列,随后再一个个地取。
遍历的时间复杂度为O(n),hasNext()与next()调用均为O(1)。
额外空间为辅助栈和数组,辅助站空间复杂度为O(h),h为树的最大深度,数组空间复杂度为O(n)。

/**
 * 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[] nums = new int[100001];
    private int size;
    private int pointer = -1;
    public BSTIterator(TreeNode root) {

        Stack<TreeNode> stack = new Stack<>();
        TreeNode p = root;
        while(p!=null||!stack.empty()){
            while (p!=null){
                stack.push(p);
                p=p.left;
            }
            p=stack.pop();
            nums[size++] = p.val;
            p = p.right;
        }
    }
    public int next() {
        return nums[++pointer];
    }
    public boolean hasNext() {
        if(pointer+1<size){
            return true;
        }
        return false;
    }
}

思路二:等价中序遍历

其实没有必要事先将整个树扁平化展开,只需记录栈和下一个要访问的结点即可。
额外的辅助空间只有栈O(h),最坏情况下,h=n,二叉树成为一条链。
hasNext()时间复杂度为O(1),Next()每一次调用的时间不同,由于每一个结点都访问至多两次,Next()取出全部的结点,因此均摊到每一次Next()的时间复杂度为O(1)。

/**
 * 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 TreeNode p;
    private Stack<TreeNode> stack = new Stack<>();
    public BSTIterator(TreeNode root) {
        p = root;
    }
    public int next() {
        int res = 0;
        while(p!=null||!stack.empty()){
            while (p!=null){
                stack.push(p);
                p=p.left;
            }
            p=stack.pop();
            res = p.val;
            p = p.right;
            break;
        }
        return res;
    }
    public boolean hasNext() {
        if(p!=null||!stack.empty()){
            return true;
        }
        return false;
    }
}
posted @ 2021-03-28 13:14  HickeyZhang  阅读(237)  评论(0)    收藏  举报