Skip to content

Commit

Permalink
Time: 49 ms (98.03%) | Memory: 52 MB (31.17%) - LeetSync
Browse files Browse the repository at this point in the history
  • Loading branch information
ShatilKhan committed Feb 27, 2024
1 parent 0892cfc commit e2443c6
Showing 1 changed file with 36 additions and 0 deletions.
36 changes: 36 additions & 0 deletions 543-diameter-of-binary-tree/diameter-of-binary-tree.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/**
* 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) {
// Define a helper function to calculate the diameter recursively
const diameter = (node, res) => {
// Base case: if the current node is null, return 0
if (!node) return 0;

// Recursively calculate the diameter of left and right subtrees
const left = diameter(node.left, res);
const right = diameter(node.right, res);

// Update the maximum diameter encountered so far
res[0] = Math.max(res[0], left + right);

// Return the depth of the current node
return Math.max(left, right) + 1;
}

// Initialize a list to hold the maximum diameter encountered
const res = [0];
// Call the diameter function starting from the root
diameter(root, res);
// Return the maximum diameter encountered
return res[0];
};

0 comments on commit e2443c6

Please sign in to comment.