Skip to content

Commit 9b747a5

Browse files
committed
Add solution #687
1 parent bcfc1f5 commit 9b747a5

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -518,6 +518,7 @@
518518
684|[Redundant Connection](./0684-redundant-connection.js)|Medium|
519519
685|[Redundant Connection II](./0685-redundant-connection-ii.js)|Hard|
520520
686|[Repeated String Match](./0686-repeated-string-match.js)|Easy|
521+
687|[Longest Univalue Path](./0687-longest-univalue-path.js)|Medium|
521522
693|[Binary Number with Alternating Bits](./0693-binary-number-with-alternating-bits.js)|Easy|
522523
695|[Max Area of Island](./0695-max-area-of-island.js)|Medium|
523524
696|[Count Binary Substrings](./0696-count-binary-substrings.js)|Easy|
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/**
2+
* 687. Longest Univalue Path
3+
* https://leetcode.com/problems/longest-univalue-path/
4+
* Difficulty: Medium
5+
*
6+
* Given the root of a binary tree, return the length of the longest path, where each node
7+
* in the path has the same value. This path may or may not pass through the root.
8+
*
9+
* The length of the path between two nodes is represented by the number of edges between them.
10+
*/
11+
12+
/**
13+
* Definition for a binary tree node.
14+
* function TreeNode(val, left, right) {
15+
* this.val = (val===undefined ? 0 : val)
16+
* this.left = (left===undefined ? null : left)
17+
* this.right = (right===undefined ? null : right)
18+
* }
19+
*/
20+
/**
21+
* @param {TreeNode} root
22+
* @return {number}
23+
*/
24+
var longestUnivaluePath = function(root) {
25+
let max = 0;
26+
dfs(root);
27+
return max;
28+
29+
function dfs(node) {
30+
if (!node) return 0;
31+
32+
const left = dfs(node.left);
33+
const right = dfs(node.right);
34+
const leftPath = node.left?.val === node.val ? left + 1 : 0;
35+
const rightPath = node.right?.val === node.val ? right + 1 : 0;
36+
37+
max = Math.max(max, leftPath + rightPath);
38+
return Math.max(leftPath, rightPath);
39+
}
40+
};

0 commit comments

Comments
 (0)