230. Kth Smallest Element in a BST

230. Kth Smallest Element in a BST

import java.util.PriorityQueue;

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */

class Solution {
 		static PriorityQueue p;

	public int kthSmallest(TreeNode root, int k) {
        p = new PriorityQueue();
		traverse(root);
		while (k !=1) {
			p.remove();
			k--;
		}
return p.peek();
	}

	private void traverse(TreeNode root) {
		if (root == null)
			return;
		traverse(root.right);
		if(root != null)p.add(root.val);
		 traverse(root.left);
	}
}

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 )

Connecting to %s