C++ solution using in-order iteration traversal


  • 0
    C
    int kthSmallest(TreeNode* root, int k) {
        int cnt = 0;
        stack<TreeNode*> stk;
        TreeNode *cur = root;
        while(root || !stk.empty()) {
            if(cur) {
                stk.push(cur);
                cur = cur->left;
            }
            else {
                TreeNode *node = stk.top();
                stk.pop();
                ++cnt;
                if(cnt == k) {
                    return node->val;
                }
                cur = node->right;
            }
        }
    }
    

    not sure about the follow-up. could any one have any idea?


Log in to reply
 

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