# Binary Tree Diameter

![](https://3743232000-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FHW2IQuh2PFpWJDvBz2FF%2Fuploads%2Fgit-blob-1ef6157c2d0781dc3784f3cfcd5609a5ad3b866e%2FScreenshot%202023-01-22%20at%2020.26.00.png?alt=media)

* n, h

```jsx
// This is an input class. Do not edit.
class BinaryTree {
  constructor(value) {
    this.value = value;
    this.left = null;
    this.right = null;
  }
}

class Diameter {
  constructor() {
    this.max = 0;
  }
}

function binaryTreeDiameter(tree) {
  const diameter = new Diameter();
  findDiameter(tree, diameter, 0);
  return diameter.max
}

function findDiameter(node, diameter, height) {
  if (node === null) {
    return 0;
  }

  const left = findDiameter(node.left, diameter);
  const right = findDiameter(node.right, diameter);

  const currentHeight = Math.max(left, right);
  const sumOfHeight = left + right;

  diameter.max = Math.max(diameter.max, sumOfHeight);

  return currentHeight + 1;
}

// Do not edit the line below.
exports.binaryTreeDiameter = binaryTreeDiameter;
exports.BinaryTree = BinaryTree;
```
