C++ Solution based on Stack


  • 1
    A
    class Solution {
    public:
        int kthSmallest(TreeNode* root, int k) {
            stack<TreeNode*> s;
            while(root || !s.empty())
            {
                if(root)
                {
                    s.push(root);
                    root=root->left;
                }
                else
                {
                    root=s.top();
                    s.pop();
                    if(--k == 0)
                        return root->val;
                    root=root->right;
                }
            }
        }
    };

Log in to reply
 

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