A simple and easy-understanding recursion Java code


  • 1
    R
     public int kthSmallest(TreeNode root, int k) {
        int leftN= findN(root.left);// find out the number of node on left subtree
        if (leftN == k-1) return root.val;
        if (leftN < k-1){
            return kthSmallest(root.right, k-leftN-1);
        }else{
            return kthSmallest(root.left, k);
        }
     }
    
     private int findN(TreeNode root){
        if (root==null) return 0;
        return 1 + findN(root.left) + findN(root.right);
     }

Log in to reply
 

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