# LeetCode: Diameter of Binary Tree Solution

Sum of max height of 2 subtrees

## Approach

Basically calculate the height of the tree

During the calculation, intercept a step which takes the sum of two subtrees' height

Get the max

## Implementation

```.css-ds3kc{display:table-row;}.css-1t8atru{display:table-cell;opacity:0.5;padding-right:var(--chakra-space-6);-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;text-align:right;}1.css-2qghsv{display:table-cell;}var diameterOfBinaryTree = function (root) {2  let max = -Infinity3
4  const recursion = node => {5    if (!node) return 06
7    let maxHeightLeft = recursion(node.left)8    let maxHeightRight = recursion(node.right)9
10    max = Math.max(max, maxHeightLeft + maxHeightRight)11
12    return Math.max(maxHeightLeft, maxHeightRight) + 113  }14
15  recursion(root)16
17  return max18}```

Original problem

## Similar problems

Diameter of N-Ary Tree

Longest Path With Different Adjacent Characters

leetcode

tree

binary tree

recursion

dfs

## Next Post

LeetCode: Kth Smallest Element in a BST

Sep 6, 2022

Inorder traversal

## Previous Post

LeetCode: Maximum Depth of Binary Tree

Sep 3, 2022

Explanation is hard

Search Posts