Skip to content

Commit dde5380

Browse files
author
luzhipeng
committed
feat: 每日一题更新2019-07-04
1 parent 924aca7 commit dde5380

File tree

2 files changed

+101
-0
lines changed

2 files changed

+101
-0
lines changed

Diff for: daily/2019-07-04.md

+96
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
## 每日一题 - longest-univalue-path
2+
3+
### 信息卡片
4+
5+
- 时间:2019-07-04
6+
- 题目链接:https://leetcode.com/problems/longest-univalue-path/
7+
- tag:`recursive` `tree`
8+
9+
### 题目描述
10+
11+
```
12+
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+
function helper(node, res) {
59+
if (node === null) return 0;
60+
const l = helper(node.left, res);
61+
const r = 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;
66+
67+
res.max = Math.max(res.max, lcnt + rcnt);
68+
69+
return Math.max(lcnt, rcnt);
70+
}
71+
/**
72+
* Definition for a binary tree node.
73+
* function TreeNode(val) {
74+
* this.val = val;
75+
* this.left = this.right = null;
76+
* }
77+
*/
78+
/**
79+
* @param {TreeNode} root
80+
* @return {number}
81+
*/
82+
var longestUnivaluePath = function(root) {
83+
const res = {
84+
max: 0
85+
};
86+
helper(root, res);
87+
return res.max;
88+
};
89+
90+
```
91+
92+
### 其他优秀解答
93+
94+
```
95+
暂无
96+
```

Diff for: daily/README.md

+5
Original file line numberDiff line numberDiff line change
@@ -95,4 +95,9 @@ tag: `binary search` `math`
9595
tag: `logic`
9696

9797
时间: 2019-07-01
98+
### [longest-univalue-path](./2019-07-04.md)
99+
100+
tag:`recursive` `tree`
101+
102+
时间: 2019-07-04
98103

0 commit comments

Comments
 (0)