Skip to content

Commit 1edfc56

Browse files
Create diameterOfBinaryTree.js
1 parent 08d8c6b commit 1edfc56

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

Trees/diameterOfBinaryTree.js

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/**
2+
* Calculates the diameter of a binary tree.
3+
* The diameter is the length of the longest path between any two nodes.
4+
* @param {TreeNode} root The root node of the tree.
5+
* @returns {number} The diameter of the tree.
6+
*/
7+
export function diameterOfBinaryTree(root) {
8+
let diameter = 0;
9+
10+
// This helper function returns the height of a subtree,
11+
// but it calculates and updates the diameter as a side effect.
12+
function height(node) {
13+
if (node === null) {
14+
return 0;
15+
}
16+
17+
const leftHeight = height(node.left);
18+
const rightHeight = height(node.right);
19+
20+
// The diameter at this node is the sum of the heights of its subtrees.
21+
// We update the global maximum diameter if this path is longer.
22+
diameter = Math.max(diameter, leftHeight + rightHeight);
23+
24+
// The height of the tree at this node is 1 + the max height of its subtrees.
25+
return 1 + Math.max(leftHeight, rightHeight);
26+
}
27+
28+
height(root);
29+
return diameter;
30+
}

0 commit comments

Comments
 (0)