Skip to content

Commit c220d33

Browse files
add: finding-the-maximum-depth-of-a-binary-tree
1 parent 25e8320 commit c220d33

File tree

2 files changed

+81
-0
lines changed

2 files changed

+81
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
# Finding the maximum depth of a binary tree
2+
3+
The maximum depth of a binary tree is the number of nodes from the root down to the furthest leaf node. In other words, it is the height of a binary tree.
4+
5+
## Input
6+
7+
```console
8+
1, 2, 3, 4, -1, 5, 6, -1, -1, -1, -1, 7, 8, -1, 9, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 10, -1, -1, -1, 11, -1
9+
```
10+
11+
Above array means below binary tree. An empty node is displayed as `-1`.
12+
13+
```console
14+
1
15+
/ \
16+
2 3
17+
/ / \
18+
4 5 6
19+
/ \ \
20+
7 8 9
21+
/ /
22+
10 11
23+
```
24+
25+
## Output
26+
27+
```console
28+
4
29+
```
30+
31+
## Execute
32+
33+
```bash
34+
node solution.js
35+
```
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
const solution = (tree) => {
2+
const makeNode = (
3+
values,
4+
offset = 0,
5+
index = 0,
6+
depth = 0,
7+
) => {
8+
if (
9+
!values ||
10+
index >= values.length ||
11+
values[index] === -1
12+
) {
13+
return null;
14+
}
15+
const left = Math.pow(2, depth) + index + offset;
16+
const right = Math.pow(2, depth) + index + 1 + offset;
17+
return {
18+
value: values[index],
19+
left: makeNode(values, 0, left, depth + 1),
20+
right: makeNode(values, 1, right, depth + 1),
21+
};
22+
};
23+
24+
const maxDepth = (node) => {
25+
if (!node) {
26+
return 0;
27+
}
28+
if (!node.left && !node.right) {
29+
return 1;
30+
}
31+
const left = maxDepth(node.left);
32+
const right = maxDepth(node.right);
33+
return Math.max(left, right) + 1;
34+
};
35+
36+
return maxDepth(makeNode(tree));
37+
};
38+
39+
(() => {
40+
const tree = [
41+
1, 2, 3, 4, -1, 5, 6, -1, -1, -1, -1, 7, 8, -1, 9, -1,
42+
-1, -1, -1, -1, -1, -1, -1, -1, -1, 10, -1, -1, -1, 11,
43+
-1,
44+
];
45+
console.log(solution(tree));
46+
})();

0 commit comments

Comments
 (0)