-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathtree.js
More file actions
135 lines (121 loc) · 2.35 KB
/
Copy pathtree.js
File metadata and controls
135 lines (121 loc) · 2.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
// 🎢 Find the Tallest Tree in a Forest (Binary Tree Maximum Depth)
// You’re walking in a forest filled with trees of different heights. A binary tree is just like a forest where each tree has branches (nodes) leading to other branches.
// Steps to Solve:
// Start from the root (base of the tree).
// Count the height of the left side and right side.
// Return the bigger height + 1 (for the root).
const maxDepth = (tree) =>{
if(!tree) return 0;
let leftHeight = maxDepth(tree.left);
let rightHeight = maxDepth(tree.right);
return Math.max(leftHeight,rightHeight) + 1
}
const treeExample = {
value: 1,
left: {
value: 2,
left: {
value: 4,
left: null,
right: null,
},
right: {
value: 5,
left: null,
right: null,
},
},
right: {
value: 3,
left: null,
right: {
value: 6,
left: null,
right: null,
},
},
};
console.log(maxDepth(treeExample));
const testCases = [
{
input: null,
expected: 0,
},
{
input: {
value: 1,
left: null,
right: null,
},
expected: 1,
},
{
input: {
value: 1,
left: {
value: 2,
left: null,
right: null,
},
right: {
value: 3,
left: null,
right: null,
},
},
expected: 2,
},
{
input: {
value: 1,
left: {
value: 2,
left: {
value: 3,
left: null,
right: null,
},
right: null,
},
right: null,
},
expected: 3,
},
{
input: {
value: 1,
left: {
value: 2,
left: null,
right: {
value: 4,
left: null,
right: null,
},
},
right: {
value: 3,
left: {
value: 5,
left: {
value: 6,
left: null,
right: null,
},
right: null,
},
right: null,
},
},
expected: 4,
},
];
// testCases.forEach((testCase, index) => {
// const result = maxDepth(testCase.input);
// console.log(
// `Test Case ${index + 1}:`,
// result === testCase.expected ? "Passed" : "Failed"
// );
// console.log(` Input: ${JSON.stringify(testCase.input)}`);
// console.log(` Expected: ${testCase.expected}, Got: ${result}`);
// });