File tree Expand file tree Collapse file tree 1 file changed +2
-5
lines changed Expand file tree Collapse file tree 1 file changed +2
-5
lines changed Original file line number Diff line number Diff line change 1
1
/**
2
2
* Calculates the diameter of a binary tree.
3
3
* 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.
4
5
* @param {TreeNode } root The root node of the tree.
5
6
* @returns {number } The diameter of the tree.
7
+ * @see {@link https://en.wikipedia.org/wiki/Tree_(graph_theory)#Properties }
6
8
*/
7
9
export function diameterOfBinaryTree ( root ) {
8
10
let diameter = 0 ;
9
11
10
- // This helper function returns the height of a subtree,
11
- // but it calculates and updates the diameter as a side effect.
12
12
function height ( node ) {
13
13
if ( node === null ) {
14
14
return 0 ;
@@ -17,11 +17,8 @@ export function diameterOfBinaryTree(root) {
17
17
const leftHeight = height ( node . left ) ;
18
18
const rightHeight = height ( node . right ) ;
19
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
20
diameter = Math . max ( diameter , leftHeight + rightHeight ) ;
23
21
24
- // The height of the tree at this node is 1 + the max height of its subtrees.
25
22
return 1 + Math . max ( leftHeight , rightHeight ) ;
26
23
}
27
24
You can’t perform that action at this time.
0 commit comments