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 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 */
79export 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
You can’t perform that action at this time.
0 commit comments