showing results for - "diameter of binary tree javascript"
Jamie
04 Aug 2018
1/**
2 * Calculate diameter with center `root`
3 * @param {TreeNode} root
4 * @returns {number}
5 */
6const countDiameter = root => {
7  if (!root) return 0;
8
9  return 1 + Math.max(countDiameter(root.left), countDiameter(root.right));
10};
11
12/**
13 * @param {TreeNode} root
14 * @returns {number}
15 */
16const diameterOfBinaryTree = root => {
17  if (!root) return 0;
18
19  const center = countDiameter(root.left) + countDiameter(root.right);
20  const left = diameterOfBinaryTree(root.left);
21  const right = diameterOfBinaryTree(root.right);
22
23  return Math.max(center, left, right);
24};
25