Tree: Level Order Traversal HackerRank Solution


Tree: Level Order Traversal HackerRank Solution
Source : https://www.hackerrank.com/challenges/tree-level-order-traversal



Source : https://www.hackerrank.com/challenges/tree-level-order-traversal


Solution


// Karthikalapati.blogspot.com
/*
class Node {
int data;
Node left;
Node right;
}
*/
// Time Complexity: O(n)
// Space Complexity: O(n)
void LevelOrder(Node root) {
ArrayDeque<Node> deque = new ArrayDeque(); // use deque as a queue
if (root != null) {
deque.add(root);
}
while (!deque.isEmpty()) {
Node n = deque.remove();
System.out.print(n.data + " ");
if (n.left != null) {
deque.add(n.left);
}
if (n.right != null) {
deque.add(n.right);
}
}
}

2 comments:

  1. This web site is usually a walk-through it really is the knowledge you desired about this and didn’t know who to inquire about. Glimpse here, and you’ll undoubtedly discover it. PUFF BAR INGREDIENTS

    ReplyDelete