Skip to content

Commit 45fb60a

Browse files
authored
Update 687-longest-univalue-path.js
1 parent 222e3fa commit 45fb60a

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

687-longest-univalue-path.js

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

0 commit comments

Comments
 (0)