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

[leetcode]Binary Search Tree Iterator

时间:2015-01-01 00:09:09      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:

使用栈来记录可能的路径,栈顶一直是下一个元素。

class BSTIterator {
public:
    stack<TreeNode *> path;
    
    BSTIterator(TreeNode *root) {
        path = stack<TreeNode *>();
        TreeNode *node = root;
        while (node != NULL) {
            path.push(node);
            node = node->left;
        }
    }

    /** @return whether we have a next smallest number */
    bool hasNext() {
        return !path.empty();
    }

    /** @return the next smallest number */
    int next() {
        TreeNode *node = path.top();
        path.pop();
        int ret = node->val;
        if (node->right != NULL) {
            node = node->right;
            path.push(node);
            while (node->left != NULL) {
                node = node->left;
                path.push(node);
            }
        }
        return ret;
    }
};

  

[leetcode]Binary Search Tree Iterator

标签:

原文地址:http://www.cnblogs.com/lautsie/p/4196759.html

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