You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Given a binary tree, find the length of the longest path where each node in the path has the same value. This path may or may not pass through the root.
13
+
14
+
The length of path between two nodes is represented by the number of edges between them.
15
+
16
+
17
+
18
+
Example 1:
19
+
20
+
Input:
21
+
22
+
5
23
+
/ \
24
+
4 5
25
+
/ \ \
26
+
1 1 5
27
+
Output: 2
28
+
29
+
30
+
31
+
Example 2:
32
+
33
+
Input:
34
+
35
+
1
36
+
/ \
37
+
4 5
38
+
/ \ \
39
+
4 4 5
40
+
Output: 2
41
+
42
+
43
+
44
+
Note: The given binary tree has not more than 10000 nodes. The height of the tree is not more than 1000.
45
+
46
+
```
47
+
48
+
### 参考答案
49
+
50
+
```js
51
+
/*
52
+
* @lc app=leetcode id=687 lang=javascript
53
+
*
54
+
* [687] Longest Univalue Path
55
+
*/
56
+
57
+
// 返回经过root的且只能取左右一个节点的路径长度
58
+
functionhelper(node, res) {
59
+
if (node ===null) return0;
60
+
constl=helper(node.left, res);
61
+
constr=helper(node.right, res);
62
+
let lcnt =0;
63
+
let rcnt =0;
64
+
if (node.left&&node.val===node.left.val) lcnt = lcnt + l +1;
65
+
if (node.right&&node.val===node.right.val) rcnt = rcnt + r +1;
0 commit comments