Skip to content

Instantly share code, notes, and snippets.

@pjcodesjs
Created March 12, 2023 05:14
Show Gist options
  • Save pjcodesjs/4e243f9f3d1b41ebdf7f9bb8f5cf9cd4 to your computer and use it in GitHub Desktop.
Save pjcodesjs/4e243f9f3d1b41ebdf7f9bb8f5cf9cd4 to your computer and use it in GitHub Desktop.
class TreeNode {
constructor(val) {
this.val = val;
this.left = null;
this.right = null;
}
}
function diameterOfBinaryTree(root) {
let diameter = 0;
function depth(node) {
if (!node) {
return 0;
}
const left = depth(node.left);
const right = depth(node.right);
diameter = Math.max(diameter, left + right);
return Math.max(left, right) + 1;
}
depth(root);
return diameter;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment