首页 > 其他 > 详细

173. Binary Search Tree Iterator

时间:2018-05-21 10:16:34      阅读:75      评论:0      收藏:0      [点我收藏+]

标签:AC   pop   called   whether   his   null   node   bsp   have   

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class BSTIterator {
public:
    stack<TreeNode *> s;
    TreeNode *p;
    BSTIterator(TreeNode *root) {
        p = root;
    }

    /** @return whether we have a next smallest number */
    bool hasNext() {
        return p != NULL || !s.empty();
    }

    /** @return the next smallest number */
    int next() {
        if (hasNext()) {
            while (p) {
                s.push(p);
                p = p->left;
            }
            p = s.top();
            s.pop();
            int val = p->val;
            p = p->right;
            return val;
        }
        return -1;
    }
};

/**
 * Your BSTIterator will be called like this:
 * BSTIterator i = BSTIterator(root);
 * while (i.hasNext()) cout << i.next();
 */

 

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class BSTIterator {
public:
    stack<TreeNode *> s;
    BSTIterator(TreeNode *root) {
        while (root) {
            s.push(root);
            root = root->left;
        }
    }

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

    /** @return the next smallest number */
    int next() {
        if (hasNext()) {
            TreeNode* p = s.top();
            s.pop();
            int val = p->val;
            p = p->right;
            while (p) {
                s.push(p);
                p = p->left;
            }
            return val;
        }
        return -1;
    }
};

/**
 * Your BSTIterator will be called like this:
 * BSTIterator i = BSTIterator(root);
 * while (i.hasNext()) cout << i.next();
 */

 

173. Binary Search Tree Iterator

标签:AC   pop   called   whether   his   null   node   bsp   have   

原文:https://www.cnblogs.com/JTechRoad/p/9065638.html

(0)
(0)
   
举报
评论 一句话评论(0
0条  
登录后才能评论!
© 2014 bubuko.com 版权所有 鲁ICP备09046678号-4
打开技术之扣,分享程序人生!
             

鲁公网安备 37021202000002号