-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathindex.js
44 lines (40 loc) · 823 Bytes
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/**
* Problem: https://leetcode.com/problems/longest-univalue-path/description/
*/
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var longestUnivaluePath = function(root) {
let max = 0;
const traverse = node => {
let len = 0, l = 0, r = 0;
if (node.left) {
l = traverse(node.left);
if (node.val === node.left.val) {
len += ++l;
} else {
l = 0;
}
}
if (node.right) {
r = traverse(node.right);
if (node.val === node.right.val) {
len += ++r;
} else {
r = 0;
}
}
max = Math.max(max, len);
return Math.max(l, r);
};
if (root) traverse(root);
return max;
};