Short and simple solution, just using inorder traversal (5 lines, 20ms)


  • 0
    5
    int kthSmallest(TreeNode* root, int &k) {
        if (root == NULL) return 0;
        int left = kthSmallest(root->left, k);
        if (--k == 0) return root->val;
        int right = kthSmallest(root->right, k);
        return left + right;
    }

  • 0
    A

    Its giving wrong output for [2,1] . Any reason why ?


  • 0
    5

    I don't understand your meaning. But it now seems likely that the code works well.


Log in to reply
 

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