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