
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
// The main function that computes the diameter of a binary tree
var diameterOfBinaryTree = function(root) {
// Initialize the diameter variable to 0
let diameter = 0;
// Call the DFS function to compute the height of each node
dfs(root);
// Return the maximum path length (diameter) found
return diameter;
// The DFS function that computes the height of each node
function dfs(root) {
// Base case: the height of a null node is 0
if(!root) return 0;
// Recursively compute the height of the left and right subtrees
let left = dfs(root.left);
let right = dfs(root.right);
// Update the diameter if the current node's diameter is greater than the previous maximum
diameter = Math.max(diameter, left + right);
// Return the height of the current node (maximum of the heights of the left and right subtrees plus one)
return Math.max(left, right) + 1;
}
};