Overview
Given the root of a binary tree, return the diameter — the length of the longest path between any two nodes. The path may or may not pass through the root. Length is measured in number of edges.
Constraints
- The number of nodes is in the range
[1, 10,000]. -100 <= Node.val <= 100
Examples
diameterOfBinaryTree([1, 2, 3, 4, 5]); // => 3 (path: 4 → 2 → 1 → 3) diameterOfBinaryTree([1, 2]); // => 1
Solution
Reveal solution
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;
}Resources
diameter-of-binary-tree.js
Diameter of Binary Tree
easycodingAlgorithmsBinary Trees
Overview
Given the root of a binary tree, return the diameter — the length of the longest path between any two nodes. The path may or may not pass through the root. Length is measured in number of edges.
Constraints
- The number of nodes is in the range
[1, 10,000]. -100 <= Node.val <= 100
Examples
diameterOfBinaryTree([1, 2, 3, 4, 5]); // => 3 (path: 4 → 2 → 1 → 3) diameterOfBinaryTree([1, 2]); // => 1
Solution
Reveal solution
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;
}Resources
NameTopicDifficulty
103 of 103 problems