Skip to content

Commit e8bf6ca

Browse files
committed
Add solution #543
1 parent f7955ef commit e8bf6ca

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -318,6 +318,7 @@
318318
521|[Longest Uncommon Subsequence I](./0521-longest-uncommon-subsequence-i.js)|Easy|
319319
541|[Reverse String II](./0541-reverse-string-ii.js)|Easy|
320320
542|[01 Matrix](./0542-01-matrix.js)|Medium|
321+
543|[Diameter of Binary Tree](./0543-diameter-of-binary-tree.js)|Easy|
321322
547|[Number of Provinces](./0547-number-of-provinces.js)|Medium|
322323
551|[Student Attendance Record I](./0551-student-attendance-record-i.js)|Easy|
323324
557|[Reverse Words in a String III](./0557-reverse-words-in-a-string-iii.js)|Easy|
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/**
2+
* 543. Diameter of Binary Tree
3+
* https://leetcode.com/problems/diameter-of-binary-tree/
4+
* Difficulty: Easy
5+
*
6+
* Given the root of a binary tree, return the length of the diameter of the tree.
7+
*
8+
* The diameter of a binary tree is the length of the longest path between any two nodes in a
9+
* tree. This path may or may not pass through the root.
10+
*
11+
* The length of a path between two nodes is represented by the number of edges between them.
12+
*/
13+
14+
/**
15+
* Definition for a binary tree node.
16+
* function TreeNode(val, left, right) {
17+
* this.val = (val===undefined ? 0 : val)
18+
* this.left = (left===undefined ? null : left)
19+
* this.right = (right===undefined ? null : right)
20+
* }
21+
*/
22+
/**
23+
* @param {TreeNode} root
24+
* @return {number}
25+
*/
26+
var diameterOfBinaryTree = function(root) {
27+
let result = 0;
28+
maxDepth(root);
29+
return result;
30+
31+
function maxDepth(node) {
32+
if (!node) return 0;
33+
const left = maxDepth(node.left);
34+
const right = maxDepth(node.right);
35+
result = Math.max(result, left + right);
36+
return Math.max(left, right) + 1;
37+
}
38+
};

0 commit comments

Comments
 (0)