Binary Search Tree Iterator (LeetCode)

Question:

https://oj.leetcode.com/problems/binary-search-tree-iterator/

 

其实就是pre-order traversal。因为每个node都只被push,pop一次,所以总的time就是O(n),对于next()来说就是O(n)/n = O(1)

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

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

    /** @return the next smallest number */
    int next() {
        
        if (curr)
        {
            s.push(curr);
            curr = curr->left;
            return next();
        }
        else
        {
            curr = s.top();
            s.pop();
            
            int value = curr->val;
            
            curr = curr->right;
            
            return value;
        }
    }

private:
    stack<TreeNode*> s;
    TreeNode* curr;
};

/**
 * 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:
    BSTIterator(TreeNode *root) {
        PushAllLeftNodes(root);
    }

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

    /** @return the next smallest number */
    int next() {
        TreeNode* node = s.top();
        s.pop();

        if (node->right)
            PushAllLeftNodes(node->right);
            
        return node->val;
    }
    
    void PushAllLeftNodes(TreeNode* node)
    {
        if (node)
        {
            s.push(node);
            PushAllLeftNodes(node->left);
        }
    }
    
private:
    stack<TreeNode*> s;
};

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

 

posted @ 2015-01-11 12:09  smileheart  阅读(152)  评论(0编辑  收藏  举报