Skip to content

Commit 924aca7

Browse files
author
luzhipeng
committed
feat: 每日一题更新答案 #687
1 parent 2fefa40 commit 924aca7

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

Diff for: daily/answers/687.longest-univalue-path.js

+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/*
2+
* @lc app=leetcode id=687 lang=javascript
3+
*
4+
* [687] Longest Univalue Path
5+
*/
6+
7+
// 返回经过root的且只能取左右一个节点的路径长度
8+
function helper(node, res) {
9+
if (node === null) return 0;
10+
const l = helper(node.left, res);
11+
const r = helper(node.right, res);
12+
let lcnt = 0;
13+
let rcnt = 0;
14+
if (node.left && node.val === node.left.val) lcnt = lcnt + l + 1;
15+
if (node.right && node.val === node.right.val) rcnt = rcnt + r + 1;
16+
17+
res.max = Math.max(res.max, lcnt + rcnt);
18+
19+
return Math.max(lcnt, rcnt);
20+
}
21+
/**
22+
* Definition for a binary tree node.
23+
* function TreeNode(val) {
24+
* this.val = val;
25+
* this.left = this.right = null;
26+
* }
27+
*/
28+
/**
29+
* @param {TreeNode} root
30+
* @return {number}
31+
*/
32+
var longestUnivaluePath = function(root) {
33+
const res = {
34+
max: 0
35+
};
36+
helper(root, res);
37+
return res.max;
38+
};

0 commit comments

Comments
 (0)