Skip to content

Commit a9948f4

Browse files
Update DiameterOfBinaryTree.js
1 parent 5c22a2c commit a9948f4

File tree

1 file changed

+2
-5
lines changed

1 file changed

+2
-5
lines changed

Trees/DiameterOfBinaryTree.js

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
11
/**
22
* Calculates the diameter of a binary tree.
33
* The diameter is the length of the longest path between any two nodes.
4+
* This path does not necessarily need to pass through the root.
45
* @param {TreeNode} root The root node of the tree.
56
* @returns {number} The diameter of the tree.
7+
* @see {@link https://en.wikipedia.org/wiki/Tree_(graph_theory)#Properties}
68
*/
79
export function diameterOfBinaryTree(root) {
810
let diameter = 0;
911

10-
// This helper function returns the height of a subtree,
11-
// but it calculates and updates the diameter as a side effect.
1212
function height(node) {
1313
if (node === null) {
1414
return 0;
@@ -17,11 +17,8 @@ export function diameterOfBinaryTree(root) {
1717
const leftHeight = height(node.left);
1818
const rightHeight = height(node.right);
1919

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.
2220
diameter = Math.max(diameter, leftHeight + rightHeight);
2321

24-
// The height of the tree at this node is 1 + the max height of its subtrees.
2522
return 1 + Math.max(leftHeight, rightHeight);
2623
}
2724

0 commit comments

Comments
 (0)