C++ solution--counting numbers of left tree

  • 4

    class Solution {


    int kthSmallest(TreeNode* root, int k) {
        if (!root) return 0;
        if (k==0) return root->val;
        int n=count_size(root->left);
        if (k==n+1) return root->val;
        if (n>=k){
            return kthSmallest(root->left, k);
        if (n<k){
            return kthSmallest(root->right, k-n-1);
    int count_size(TreeNode* root){
        if (!root) return 0;
        return 1+count_size(root->left)+count_size(root->right);


  • 0

    @sophie2509 In this, size of sub-trees are computed repeatedly which is slow. Rather, go inorder(bottom-up for left sub tree and top-down for right sub tree) and whenever size equals k, return the node.

Log in to reply

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