My code for 1ms


  • 0
    Z

    public int kthSmallest(TreeNode root, int k) {
    if(root==null)
    return 0;

       if(k-1==numberOfTree(root.left))
           return root.val;
         
        if(k<=numberOfTree(root.left)){
            return kthSmallest(root.left,k);
        }
        
        return kthSmallest(root.right,k-1-numberOfTree(root.left));
    }
    
    public int numberOfTree(TreeNode root){
        if(root==null)
            return 0;
          
        if(root.left==null&&root.right==null)
            return 1;
            
        return numberOfTree(root.left)+numberOfTree(root.right)+1;
    }

Log in to reply
 

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