Skip to content

Commit 46d4e77

Browse files
authored
Create 687-longest-univalue-path.js
1 parent 42029fb commit 46d4e77

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

687-longest-univalue-path.js

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* function TreeNode(val) {
4+
* this.val = val;
5+
* this.left = this.right = null;
6+
* }
7+
*/
8+
/**
9+
* @param {TreeNode} root
10+
* @return {number}
11+
*/
12+
const getCount = function(root, longest) {
13+
if (!root) {
14+
return 0;
15+
}
16+
let leftCount = getCount(root.left, longest);
17+
let rightCount = getCount(root.right, longest);
18+
if (root.left && root.left.val === root.val) {
19+
leftCount++;
20+
} else {
21+
leftCount = 0;
22+
}
23+
if (root.right && root.right.val === root.val) {
24+
rightCount++;
25+
} else {
26+
rightCount = 0;
27+
}
28+
longest.max = Math.max(longest.max, leftCount + rightCount);
29+
return Math.max(leftCount, rightCount);
30+
};
31+
32+
const longestUnivaluePath = function(root) {
33+
let longest = { max: 0 };
34+
getCount(root, longest);
35+
return longest.max;
36+
};

0 commit comments

Comments
 (0)