173. Binary Search Tree Iterator

来源:互联网 发布:安装ubuntu系统 编辑:程序博客网 时间:2024/06/05 14:25

这是一道OOD的题目,通过自己打包已经就绪的一些数据结构,进行iterator的设计,这里是对BST设计interator

我很傻很天真的用了一个Queue来实现,也就是把BST线性化,可是题目要求的是存储空间是O(h),h是BST的高度,而我的方法用了O(n)

BUT 还是先把码贴过来,自己在实现一遍,最后实现O(h)的方法。

/** * Definition for binary tree * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */// 跟面试官解释:basic idea 就是把BST进行inorder travesal,and store the value in a queue. 然后就可以执行时hasNext(), next()的方法,用isEmpty()和pop().intValue()来实现。。都是O(1)时间。。public class BSTIterator {    //List<Integer> list= new ArrayList<Integer>();  // when coding towards end, I found that indexing is a little problematic for ArrayList for the required time and space complexity, so I change to use queue, since there is build-in functions such as: pop(), isEmpty() in queue.        Queue<Integer> list;        public BSTIterator(TreeNode root) {        list = new LinkedList<Integer>();        //if(root==null) return;        fillList(root, list);    }        // design a helper for adding node.val to list Iterratively, basically it is the in order traversal    public void fillList(TreeNode node, Queue<Integer> list){   /*       if(node.left==null && node.right==null) list.add(node.val);        fillList(node.left, list);        list.add(node.val);        fillList(node.right, list);*/   // 这里我犯了个低级错误。。。把二叉树的 中序遍历都搞错了!!!看了之前自己的实现才发现。。看来 在这种情况下,不能把叶子节点作为base case,只能普遍的说null时,不做任何处理,所以base case 不用写!!!只要写base case的反面,if(node!=null) ...然后中序遍历!!!总结总结!!!        if(node!=null){            fillList(node.left, list);            list.add(node.val);  //!!! inorder traversal 要熟悉啊!!三部曲:if not null, arrange the order, core operation+ recursive            fillList(node.right, list);        }    }            /** @return whether we have a next smallest number */    public boolean hasNext() {        return !list.isEmpty();    }    /** @return the next smallest number */    public int next() {        return list.poll().intValue();    }}/** * Your BSTIterator will be called like this: * BSTIterator i = new BSTIterator(root); * while (i.hasNext()) v[f()] = i.next(); */


今天的代码,重复实现一下用Queue来设计Iterator

/** * Definition for binary tree * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class BSTIterator {        Queue<Integer> list;    public BSTIterator(TreeNode root) {        list = new LinkedList<Integer>();        fill(list, root);    }        public void fill(Queue<Integer> list, TreeNode root){        if(root!=null){            fill(list, root.left);            list.add(root.val);            fill(list, root.right);        }    }        /** @return whether we have a next smallest number */    public boolean hasNext() {        return !list.isEmpty();    }    /** @return the next smallest number */    public int next() {        return list.poll().intValue(); // .poll() !! 不是 .pop()    }}/** * Your BSTIterator will be called like this: * BSTIterator i = new BSTIterator(root); * while (i.hasNext()) v[f()] = i.next(); */


今天的代码,用Stack来实现Iterator,这里可以达到存储空间是O(h)

思路其实很简单,就是把最左的所有节点挨个压入stack,使得stack的顶部的元素始终是最小的元素。要注意的是在弹出最小元素的node后,要考察它有没有右节点,如果有要压入,然后把这个右节点当作是构造函数中的root,还是要依次压入左边节点。。。才能亦然维护stack顶端的元素是最小的。。。

/** * Definition for binary tree * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class BSTIterator {    Stack<TreeNode> stack;    public BSTIterator(TreeNode root) {        stack = new Stack<TreeNode>();        while(root!=null){ // 把所有左节点依次全部压入stack,stack顶部就是最小值了!            stack.push(root);            root=root.left;        }    }    /** @return whether we have a next smallest number */    public boolean hasNext() {        return !stack.isEmpty();    }    /** @return the next smallest number */    public int next() {        TreeNode curr= stack.pop(); // 因为stack的顶部总是最小值,所以直接pop就可以了,但是要依然维护stack最上元素是整个tree中最小的node        int result= curr.val;        if(curr.right!=null){       // (接上)因此要看这个弹出的node是否有right child,然后right child是否有left child,相当于把车node当作上面构造函数中的root来处理了            curr=curr.right;                    stack.push(curr);            while(curr.left!=null){                curr=curr.left;                stack.push(curr);            }        }        return result;    }}/** * Your BSTIterator will be called like this: * BSTIterator i = new BSTIterator(root); * while (i.hasNext()) v[f()] = i.next(); */






0 0
原创粉丝点击