diameter of ninary tree code example

Example 1: get diameter of binary tree

int getDiameter(TreeNode* root)
{
	if(root == NULL)
    	return(0);
    int lheight = getHeight(root->left);
    int rheight = getHeight(root->right);
    
    int ldiameter = getDiameter(root->left);
    int rdiameter = getDiameter(root->right);
    
    return(max(lheight+rheight+1,max(ldiameter,rdiameter)));
}

Example 2: diameter of binary tree javascript

/**
 * Calculate diameter with center `root`
 * @param {TreeNode} root
 * @returns {number}
 */
const countDiameter = root => {
  if (!root) return 0;

  return 1 + Math.max(countDiameter(root.left), countDiameter(root.right));
};

/**
 * @param {TreeNode} root
 * @returns {number}
 */
const diameterOfBinaryTree = root => {
  if (!root) return 0;

  const center = countDiameter(root.left) + countDiameter(root.right);
  const left = diameterOfBinaryTree(root.left);
  const right = diameterOfBinaryTree(root.right);

  return Math.max(center, left, right);
};