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

Binary Search Tree Iterator

时间:2015-08-25 21:21:37      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:

开始主要是不知道这道题想表达什么意思,知道他想表达什么意思之后就很简单了。

思路:找最小值,可以参考中序遍历,借助栈!每弹出一个元素,才增加栈中元素,不用马上遍历整颗树!

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

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

    /** @return the next smallest number */
    int next() {
        TreeNode*temp=stk.top();
        stk.pop();
        int res=temp->val;
        temp=temp->right;
        while(temp)
        {
            stk.push(temp);
            temp=temp->left;
        }
        return res;
    }
};

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

  

Binary Search Tree Iterator

标签:

原文地址:http://www.cnblogs.com/qiaozhoulin/p/4758506.html

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