Binary Search Tree Iterator

完全没有想法

实际上是in order traversal而已

public class BSTIterator {
    public TreeNode crt;
    public Stack<TreeNode> st = new Stack<TreeNode>();
    
    public BSTIterator(TreeNode root) {
        crt = root;
    }

    /** @return whether we have a next smallest number */
    public boolean hasNext() {
        return (crt!=null||!st.isEmpty());        
    }

    /** @return the next smallest number */
    public int next() {
        while(crt!=null){
            st.push(crt);
            crt = crt.left;
        }
        crt = st.pop();
        int res =crt.val;
        crt = crt.right;
        return res;
    }
}

 

posted @ 2015-06-17 05:05  世界到处都是小星星  阅读(96)  评论(0编辑  收藏  举报