A Simple Recursive Solution in Java


  • 0
    H
    public int kthSmallest(TreeNode root, int k) {
        if (k == this.countChildren(root.left) + 1) {
            return root.val;
        }
        if (k < this.countChildren(root.left) + 1) {
            return this.kthSmallest(root.left, k);
        }
        if (k > this.countChildren(root.left) + 1) {
            return this.kthSmallest(root.right, k - this.countChildren(root.left) - 1);
        }
        return 0;
    }
    public int countChildren(TreeNode root) {
        if (root != null) {
            return this.countChildren(root.left) + this.countChildren(root.right) + 1;
        } else {
            return 0;
        }
    }

Log in to reply
 

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