码迷,mamicode.com
首页 > 其他好文 > 详细

Binary Search Tree Iterator

时间:2015-06-17 07:06:12      阅读:90      评论:0      收藏:0      [点我收藏+]

标签:

完全没有想法

实际上是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;
    }
}

 

Binary Search Tree Iterator

标签:

原文地址:http://www.cnblogs.com/jiajiaxingxing/p/4582277.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!