Kth Smallest Element in a BST

Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.

 


/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public int kthSmallest(TreeNode root, int k) {
        //BST -> sorted binary tree 
        //count the number of nodes in the left tree 
        int count = countNode (root.left); 
        if (k <= count) {
            //it means the purpose node lies in the children of the root.
            return kthSmallest(root.left, k);
        } else if (k > count + 1) {
            //it means the purpose node lies in the children of the root.
            return kthSmallest(root.right, k-1-count);
        }
        return root.val; 
    }
    
    public int countNode (TreeNode n) {
        if (n == null) return 0; 
        return 1 + countNode(n.left) + countNode(n.right);
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s