程式語言 - LeetCode - C++ - 173. Binary Search Tree Iterator



題目:


解答:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class BSTIterator {
public:
    void push_left(TreeNode* n) {
        while (n) {
            st.push(n);
            n = n->left;
        }
    }

    BSTIterator(TreeNode* root) {
        push_left(root);
    }
    
    int next() {
        TreeNode *t = st.top(); st.pop();

        if (t->right) {
            push_left(t->right);
        }

        return t->val;
    }
    
    bool hasNext() {
        return !st.empty();
    }

private:
    stack<TreeNode*> st;
};

/**
 * Your BSTIterator object will be instantiated and called as such:
 * BSTIterator* obj = new BSTIterator(root);
 * int param_1 = obj->next();
 * bool param_2 = obj->hasNext();
 */