Skip to content

Commit 746259e

Browse files
committed
Added Level Order Traversal Algorithm
1 parent 0dc0396 commit 746259e

File tree

1 file changed

+296
-0
lines changed

1 file changed

+296
-0
lines changed
Lines changed: 296 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,296 @@
1+
---
2+
id: level-order-traversal
3+
title: Level Order Traversal
4+
sidebar_label: Level Order Traversal
5+
tags:
6+
- Tree
7+
- Breadth-First Search
8+
- Binary Tree
9+
description: "This is a solution to the Binary Tree Level Order Traversal problem on LeetCode."
10+
---
11+
12+
## Problem Description
13+
Given the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level).
14+
15+
### Examples
16+
17+
**Example 1:**
18+
![image](https://assets.leetcode.com/uploads/2021/02/19/tree1.jpg)
19+
```
20+
Input: root = [3,9,20,null,null,15,7]
21+
Output: [[3],[9,20],[15,7]]
22+
```
23+
24+
**Example 2:**
25+
```
26+
Input: root = [1]
27+
Output: [[1]]
28+
```
29+
30+
31+
### Constraints
32+
- The number of nodes in the tree is in the range [0, 2000].
33+
- `-1000 <= Node.val <= 1000`
34+
35+
## Solution for Binary Tree Level Order Traversal
36+
37+
### Intuition
38+
- To perform a level-order traversal on a binary tree and store the nodes’ values in a 2D vector representing each level, start by initialising an empty queue to hold the level by level nodes.Enqueue the root node into the queue and traverse until the queue is empty. For each level, track the number of nodes in that level, creating a temporary vector to deque and store them. At each node, store its value in the temporary vector and enqueue its left and right children if they exist.Once all the nodes at a level are processed add this 1D temporary vector to the final 2D vector, representing that level. This process repeats until all levels are traversed. Finally, return this 2D vector containing the level order traversal of the binary tree.
39+
<Tabs>
40+
<TabItem value="Solution" label="Solution">
41+
#### Implementation
42+
43+
```jsx live
44+
function Solution() {
45+
function TreeNode(val = 0, left = null, right = null) {
46+
this.val = val;
47+
this.left = left;
48+
this.right = right;
49+
}
50+
function constructTreeFromArray(array) {
51+
if (!array.length) return null;
52+
53+
let root = new TreeNode(array[0]);
54+
let queue = [root];
55+
let i = 1;
56+
57+
while (i < array.length) {
58+
let currentNode = queue.shift();
59+
60+
if (array[i] !== null) {
61+
currentNode.left = new TreeNode(array[i]);
62+
queue.push(currentNode.left);
63+
}
64+
i++;
65+
66+
if (i < array.length && array[i] !== null) {
67+
currentNode.right = new TreeNode(array[i]);
68+
queue.push(currentNode.right);
69+
}
70+
i++;
71+
}
72+
return root;
73+
}
74+
function levelOrder(root) {
75+
if (!root) return [];
76+
77+
const queue = [root];
78+
const ans = [];
79+
80+
while (queue.length > 0) {
81+
const size = queue.length;
82+
const temp = [];
83+
84+
for (let i = 0; i < size; i++) {
85+
const curr = queue.shift();
86+
87+
if (curr.left) queue.push(curr.left);
88+
if (curr.right) queue.push(curr.right);
89+
90+
temp.push(curr.val);
91+
}
92+
93+
ans.push(temp);
94+
}
95+
96+
return ans;
97+
}
98+
99+
100+
const array = [3,9,20,null,null,15,7]
101+
const input = constructTreeFromArray(array)
102+
const output = levelOrder(input)
103+
return (
104+
<div>
105+
<p>
106+
<b>Input: </b>{JSON.stringify(array)}
107+
</p>
108+
<p>
109+
<b>Output:</b> {output.toString()}
110+
</p>
111+
</div>
112+
);
113+
}
114+
```
115+
116+
### Code in Different Languages
117+
118+
<Tabs>
119+
<TabItem value="JavaScript" label="JavaScript">
120+
<SolutionAuthor name="@hiteshgahanolia"/>
121+
```javascript
122+
```
123+
</TabItem>
124+
<TabItem value="TypeScript" label="TypeScript">
125+
<SolutionAuthor name="@hiteshgahanolia"/>
126+
```typescript
127+
class TreeNode {
128+
val: number;
129+
left: TreeNode | null;
130+
right: TreeNode | null;
131+
constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
132+
this.val = (val === undefined ? 0 : val);
133+
this.left = (left === undefined ? null : left);
134+
this.right = (right === undefined ? null : right);
135+
}
136+
}
137+
138+
function levelOrder(root: TreeNode | null): number[][] {
139+
if (!root) return [];
140+
141+
const queue: TreeNode[] = [root];
142+
const ans: number[][] = [];
143+
144+
while (queue.length > 0) {
145+
const size = queue.length;
146+
const temp: number[] = [];
147+
148+
for (let i = 0; i < size; i++) {
149+
const curr = queue.shift()!;
150+
151+
if (curr.left) queue.push(curr.left);
152+
if (curr.right) queue.push(curr.right);
153+
154+
temp.push(curr.val);
155+
}
156+
157+
ans.push(temp);
158+
}
159+
160+
return ans;
161+
}
162+
```
163+
</TabItem>
164+
<TabItem value="Python" label="Python">
165+
<SolutionAuthor name="@hiteshgahanolia"/>
166+
```python
167+
from collections import deque
168+
class TreeNode:
169+
def __init__(self, val=0, left=None, right=None):
170+
self.val = val
171+
self.left = left
172+
self.right = right
173+
174+
class Solution:
175+
def levelOrder(self, root: TreeNode) -> List[List[int]]:
176+
if not root:
177+
return []
178+
179+
q = deque([root])
180+
ans = []
181+
182+
while q:
183+
size = len(q)
184+
temp = []
185+
186+
for _ in range(size):
187+
curr = q.popleft()
188+
189+
if curr.left:
190+
q.append(curr.left)
191+
if curr.right:
192+
q.append(curr.right)
193+
194+
temp.append(curr.val)
195+
196+
ans.append(temp)
197+
198+
return ans
199+
```
200+
</TabItem>
201+
<TabItem value="Java" label="Java">
202+
<SolutionAuthor name="@hiteshgahanolia"/>
203+
```java
204+
import java.util.*;
205+
206+
class TreeNode {
207+
int val;
208+
TreeNode left;
209+
TreeNode right;
210+
TreeNode(int x) { val = x; }
211+
}
212+
213+
class Solution {
214+
public List<List<Integer>> levelOrder(TreeNode root) {
215+
Queue<TreeNode> q = new LinkedList<>();
216+
List<List<Integer>> ans = new ArrayList<>();
217+
218+
if (root == null) return ans;
219+
220+
q.offer(root);
221+
222+
while (!q.isEmpty()) {
223+
int size = q.size();
224+
List<Integer> temp = new ArrayList<>();
225+
226+
for (int i = 0; i < size; i++) {
227+
TreeNode curr = q.poll();
228+
229+
if (curr.left != null) q.offer(curr.left);
230+
if (curr.right != null) q.offer(curr.right);
231+
232+
temp.add(curr.val);
233+
}
234+
235+
ans.add(temp);
236+
}
237+
238+
return ans;
239+
}
240+
}
241+
242+
```
243+
</TabItem>
244+
<TabItem value="C++" label="C++">
245+
<SolutionAuthor name="@hiteshgahanolia"/>
246+
```cpp
247+
class Solution {
248+
public:
249+
vector<vector<int>> levelOrder(TreeNode* root) {
250+
queue<TreeNode *> q;
251+
vector<vector<int>> ans;
252+
253+
if(!root) return ans;
254+
255+
q.push(root);
256+
257+
while(!q.empty()){
258+
int size = q.size();
259+
vector<int> temp;
260+
261+
while(size--){
262+
TreeNode *curr = q.front();
263+
q.pop();
264+
265+
if(curr->left) q.push(curr->left);
266+
if(curr->right) q.push(curr->right);
267+
268+
temp.push_back(curr->val);
269+
}
270+
271+
ans.push_back(temp);
272+
}
273+
274+
return ans;
275+
}
276+
};
277+
```
278+
</TabItem>
279+
</Tabs>
280+
281+
#### Complexity Analysis
282+
##### Time Complexity:
283+
- $O(N)$ where N is the number of nodes in the binary tree. Each node of the binary tree is enqueued and dequeued exactly once, hence all nodes need to be processed and visited. Processing each node takes constant time operations which contributes to the overall linear time complexity.
284+
285+
##### Space Complexity:
286+
- $O(N)$ where N is the number of nodes in the binary tree. In the worst case, the queue has to hold all the nodes of the last level of the binary tree, the last level could at most hold N/2 nodes hence the space complexity of the queue is proportional to $O(N)$.The resultant vector answer also stores the values of the nodes level by level and hence contains all the nodes of the tree contributing to O(N) space as well.
287+
288+
</TabItem>
289+
</Tabs>
290+
291+
## References
292+
293+
- **LeetCode Problem**: [Binary Tree Level Order Traversal](https://leetcode.com/problems/binary-tree-level-order-traversal/)
294+
295+
- **Solution Link**: [LeetCode Solution](hhttps://leetcode.com/problems/binary-tree-level-order-traversal/solutions)
296+

0 commit comments

Comments
 (0)