File tree Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments