8 May 2024
Easy
543. Diameter of Binary Tree
Link: https://leetcode.com/problems/diameter-of-binary-tree
Description: Given the root of a binary tree, return the diameter of the tree.
Solution:
Calculate the depth of the left and right subtrees of the current node recursively. The diameter of the current node is the maximum of the sum of the depth of the left and right subtrees. If the root is null, we return 0. Otherwise, we recursively calculate the depth of the left and right subtrees of the current node.
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var diameterOfBinaryTree = function (root) {
let diameter = 0
function depth(node) {
if (!node) return 0
let leftDepth = depth(node.left)
let rightDepth = depth(node.right)
diameter = Math.max(diameter, leftDepth + rightDepth)
return 1 + Math.max(leftDepth, rightDepth)
}
depth(root)
return diameter
}