Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 0a3d5e6

Browse files
author
Swastikyadav
committed
Add levelWidth solution
1 parent 406023b commit 0a3d5e6

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

‎DsAlgo-Questions/23-levelWidth.js

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/*
2+
Given the array of a tree, return an array where each element is the width of the tree at each level.
3+
4+
--Example
5+
Given:
6+
7+
0
8+
/ | \
9+
1 2 3
10+
| |
11+
4 5
12+
13+
Answer: [1, 3, 2]
14+
*/
15+
16+
function levelWidth(root) {
17+
const counterArr = [0];
18+
const arr = [root, null];
19+
20+
while (arr.length > 1) {
21+
const node = arr.shift();
22+
23+
if (node === null) {
24+
counterArr.push(0);
25+
arr.push(null);
26+
} else {
27+
arr.push(...node.children);
28+
counterArr[counterArr.length - 1]++;
29+
}
30+
}
31+
32+
return counterArr;
33+
}
34+
35+
// Solution technique: Breadth first search with a stoper (null) pointer / variable.

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /