Print Kth Level of BST

Print values of nodes in kth level of a BST.

public class Soltuion {
    public void printKthNode(TreeNode root, int k) {
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int currentLevel = 0;
        
        while (!queue.isEmpty()) {
            int size = queue.size();
            // When it reaches level k
            if (currentLeve == k) {
                for(int i = 0; i < size; i++) {
                    TreeNode node = queue.poll;
                    System.out.println(node.val);
                }
            return;
            }
            // Not level k
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
            }
            currentLevel++;
        }
    }
}
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