We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Better clarity in the comments
public static void levelOrder(Node root) {
// Use ArrayDeque as the queue for level order traversal
Queue nodeQueue = new ArrayDeque<>();
// Start by offering the root node to the queue
nodeQueue.offer(root);
// Process nodes until the queue is empty
while (nodeQueue.size() > 0) {
// Remove the front element from the queue
Node node = nodeQueue.poll();
// Print the current node's data
System.out.print(node.data + " ");
// If the left child is not null, add it to the queue
if (node.left != null) {
nodeQueue.offer(node.left);
}
// If the right child is not null, add it to the queue
if (node.right != null) {
nodeQueue.offer(node.right);
}
}
}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Tree: Level Order Traversal
You are viewing a single comment's thread. Return to all comments →
Better clarity in the comments public static void levelOrder(Node root) { // Use ArrayDeque as the queue for level order traversal Queue nodeQueue = new ArrayDeque<>();