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
{
    private:
        stack<TreeNode*> stk;

    public:
        BSTIterator(TreeNode* root)
        {
            while (root)
            {
                // 探索左邊的樹
                stk.push(root);
                root = root->left;
            }
        }

    int next()
    {
        TreeNode* node = stk.top(); stk.pop();

        // 回傳 node_val 的值
        int node_val = node->val;

        // 如果有右子樹的話,探索右邊的樹
        if (node->right)
        {
            // 指標到下一個節點
            node = node->right;

            // 如果 node 存在的話
            while (node)
            {
                // 將右子樹的所有左子節點再次推入 stack 中。
                stk.push(node);
                node = node->left;
            }
        }

        return node_val;
    }

    bool hasNext()
    {
        return !stk.empty();
    }
};

/**
 * 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();
 */
  • T: O()O()
  • S: O()O()