2. Level Order Traversal
The problem can be found at the following link: Problem Link
Problem Description
Given the root of a binary tree with n
nodes, the task is to find its level order traversal.
Level order traversal of a tree is breadth-first traversal for the tree, where we visit nodes level by level.
Examples:
Example 1
Input:
root[] = [1, 2, 3]
Output:
[[1], [2, 3]]
Example 2
Input:
root[] = [10, 20, 30, 40, 50]
Output:
[[10], [20, 30], [40, 50]]
Example 3
Input:
root[] = [1, 3, 2, N, N, N, 4, 6, 5]
Output:
[[1], [3, 2], [4], [6, 5]]
Constraints
1 β€ number of nodes β€ $10^5$
0 β€ node->data β€ $10^9$
My Approach
Use a queue to traverse the tree level by level.
Start by pushing the root node into the queue.
Process each level:
Store the number of nodes in the current level.
Traverse all nodes of the level, adding them to the result.
Push their left and right children (if they exist) into the queue.
Continue the process until all nodes are visited.
This approach ensures that each node is visited exactly once, making it efficient and optimal for level-order traversal.
Time and Auxiliary Space Complexity
Expected Time Complexity:
O(n)
, wheren
is the number of nodes in the tree. Each node is visited exactly once.Expected Auxiliary Space Complexity:
O(n)
, since, in the worst case, we store all nodes in the queue.
Code (C++)
class Solution {
public:
vector<vector<int>> levelOrder(Node *root) {
if (!root) return {};
queue<Node *> q({root});
vector<vector<int>> res;
while (!q.empty()) {
res.push_back({});
for (int i = q.size(); i > 0; i--) {
Node *n = q.front(); q.pop();
res.back().push_back(n->data);
if (n->left) q.push(n->left);
if (n->right) q.push(n->right);
}
}
return res;
}
};
Code (Java)
class Solution {
public ArrayList<ArrayList<Integer>> levelOrder(Node root) {
ArrayList<ArrayList<Integer>> res = new ArrayList<>();
if (root == null) return res;
Queue<Node> q = new LinkedList<>();
q.add(root);
while (!q.isEmpty()) {
ArrayList<Integer> level = new ArrayList<>();
for (int i = q.size(); i > 0; i--) {
Node n = q.poll();
level.add(n.data);
if (n.left != null) q.add(n.left);
if (n.right != null) q.add(n.right);
}
res.add(level);
}
return res;
}
}
Code (Python)
class Solution:
def levelOrder(self, root):
if not root: return []
res, q = [], [root]
while q:
res.append([n.data for n in q])
q = [c for n in q for c in (n.left, n.right) if c]
return res
Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Letβs make this learning journey more collaborative!
β If you find this helpful, please give this repository a star! β
πVisitor Count
Last updated