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

LeetCode Binary Search Tree Iterator

时间:2015-01-23 00:37:56      阅读:226      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!