首页 > 其他 > 详细

LeetCode Binary Search Tree Iterator

时间:2015-01-23 00:35:03      阅读:330      评论:0      收藏:0      [点我收藏+]
class BSTIterator {
private:
    TreeNode* current;
    stack<TreeNode*> nodeStack;
public:
    BSTIterator(TreeNode *root) {
        current = root;
    }

    /** @return whether we have a next smallest number */
    bool hasNext() {
        if (nodeStack.empty() && current == NULL) {
            return false;
        } else {
            return true;
        }
    }

    /** @return the next smallest number */
    int next() {
        while (current != NULL) {
            nodeStack.push(current);
            current = current->left;
        }
        // node current must be null,
        // the last one pushed in the stack must be the smallest one
        
        TreeNode* last = nodeStack.top();
        nodeStack.pop();
        
        // next we will start from its right sub-tree to find the smallest one
        current = last->right;

        return last->val;
    }
};

好久没写了,最近一直吃翔,看到运行时间分布,Java居然被许多Python超了,看来python大法确实好啊

LeetCode Binary Search Tree Iterator

原文:http://www.cnblogs.com/lailailai/p/4243016.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!