FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
algorithm/Week_01/id_140/Leetcode_687_140.java at master · isnotnull/algorithm · GitHub
isnotnull
/
algorithm
Public
forked from
algorithm001/algorithm
Notifications
You must be signed in to change notification settings
Fork
0
Star
0
Code
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
algorithm
/
Week_01
/
id_140
/
Leetcode_687_140.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
90 lines (80 loc) · 1.87 KB
Breadcrumbs
algorithm
/
Week_01
/
id_140
/
Leetcode_687_140.java
Copy path
File metadata and controls
90 lines (80 loc) · 1.87 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/**
* 给定一个二叉树,找到最长的路径,这个路径中的每个节点具有相同值。 这条路径可以经过也可以不经过根节点。
* <p>
* 注意:两个节点之间的路径长度由它们之间的边数表示。
* <p>
* 示例 1:
* <p>
* 输入:
* <p>
* 5
* / \
* 4 5
* / \ \
* 1 1 5
* 输出:
* <p>
* 2
* 示例 2:
* <p>
* 输入:
* <p>
* 1
* / \
* 4 5
* / \ \
* 4 4 5
* 输出:
* <p>
* 2
* 注意: 给定的二叉树不超过10000个结点。 树的高度不超过1000。
*/
public
class
Leetcode_687_140
{
/**
* 调用入口
* @param root
* @return
*/
public
int
longestUnivaluePath
(
TreeNode
root
) {
int
[]
answer
=
new
int
[
1
];
dfs
(
root
,
answer
);
return
answer
[
0
];
}
/**
* 返回数值一样最长的那个节点的值
* @param root
* @param answer
* @return
*/
private
int
dfs
(
TreeNode
root
,
int
[]
answer
) {
if
(
root
==
null
) {
return
0
;
}
int
leftLength
=
dfs
(
root
.
left
,
answer
);
int
rightLength
=
dfs
(
root
.
right
,
answer
);
int
maxUnival
=
0
;
if
(
root
.
left
!=
null
&&
root
.
val
==
root
.
left
.
val
) {
maxUnival
+=
leftLength
+
1
;
}
if
(
root
.
right
!=
null
&&
root
.
val
==
root
.
right
.
val
) {
maxUnival
+=
rightLength
+
1
;
}
answer
[
0
] =
Math
.
max
(
answer
[
0
],
maxUnival
);
int
returnVal
=
0
;
if
(
root
.
left
!=
null
&&
root
.
left
.
val
==
root
.
val
) {
returnVal
=
leftLength
+
1
;
}
if
(
root
.
right
!=
null
&&
root
.
right
.
val
==
root
.
val
) {
returnVal
=
Math
.
max
(
returnVal
,
rightLength
+
1
);
}
return
returnVal
;
}
public
class
TreeNode
{
int
val
;
TreeNode
left
;
TreeNode
right
;
TreeNode
(
int
x
) {
val
=
x
;
}
}
}
Back
|
FazBrowse Home
|
New Git URL