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

Leetcode[]-Binary Search Tree Iterator

时间:2015-06-13 09:56:01      阅读:100      评论:0      收藏:0      [点我收藏+]

标签:iterator   tree   search   return   

Implement an iterator over a binary search tree (BST). Your iterator will be initialized with the root node of a BST.

Calling next() will return the next smallest number in the BST.

Note: next() and hasNext() should run in average O(1) time and uses O(h) memory, where h is the height of the tree.


思路: 遍历一遍,然后从小到大的放到队列里去,然后判断队列是否非空,不非空则前面的就是最小的,出队即可!

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class BSTIterator {
public:
    queue<int> que;
    BSTIterator(TreeNode *root) {
        stack<TreeNode *> stk;
        map<TreeNode *, int> visited;
        TreeNode *p;
        if(root) { 
            stk.push(root);
            visited[root] = 0;
        }
        while(!stk.empty()){
            p = stk.top();
            while(p->left && visited[p] == 0){
                if(visited[p->left] == 1) break;
                p = p->left;
                stk.push(p);
                visited[p]=0;
            }
            visited[p]=1;
            que.push(p->val);
            stk.pop();

            if(p->right && (visited.find(p->right)==visited.end() || visited[p->right]==0)){
                stk.push(p->right);
                visited[p->right] = 0;
                continue;
            }
        }



    /* another way     
    stack<TreeNode*> stk;
        while(root || !stk.empty() ) {
            if(root){
                stk.push(root);
                root = root->left;
            }else {
                root = stk.top();
                stk.pop();
                que.push(root->val);
                root = root->right;
            }   
        } */ 
    }

/** @return whether we have a next smallest number */
    bool hasNext() {
        if(!que.empty()) return true;
        return false;
    }
/** @return the next smallest number */
    int next() {
        int val = que.front();
        que.pop();
        return val;
    }
};

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

Leetcode[]-Binary Search Tree Iterator

标签:iterator   tree   search   return   

原文地址:http://blog.csdn.net/dream_angel_z/article/details/46476219

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