C++ Iterative solution using a stack 20ms


  • 0
    R

    The wanted element is the last element pop from the stack. Classic traversal solution.

    Solution {
        public:
            int kthSmallest(TreeNode* root, int k) {
                TreeNode* current = root;
                stack<TreeNode*> s;
                int count = 0;
                TreeNode* tmp;
                while(count < k){
                    if(current != NULL){
                        s.push(current);
                        current = current->left;
                    }else{
                        tmp = s.top();
                        s.pop();
                        count++;
                        current = tmp->right;
                    }
                }
                return tmp->val;
            }
        };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.