首页 > 其他 > 详细

[leetcode]Binary Search Tree Iterator

时间:2015-01-01 00:06:39      阅读:362      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!