FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
algorithm/Week_02/id_118/leetcode_236_118.java at master · algorithm001/algorithm · GitHub
algorithm001
/
algorithm
Public
Notifications
You must be signed in to change notification settings
Fork
148
Star
118
Code
Issues
548
Pull requests
46
Actions
Projects
Wiki
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Projects
Wiki
Security and quality
Insights
Expand file tree
Breadcrumbs
algorithm
/
Week_02
/
id_118
/
leetcode_236_118.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
55 lines (50 loc) · 1.65 KB
Breadcrumbs
algorithm
/
Week_02
/
id_118
/
leetcode_236_118.java
Copy path
File metadata and controls
55 lines (50 loc) · 1.65 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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
// https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree/submissions/
// 236.二叉树的最近公共祖先
class
Solution
{
public
TreeNode
lowestCommonAncestor
(
TreeNode
root
,
TreeNode
p
,
TreeNode
q
) {
// root有任何一个是根节点,则它本身就是最近公共祖先
if
(
p
==
root
||
q
==
root
){
return
root
;
}
// 判断:p和q在不在左子树上
boolean
pLeft
=
find
(
root
.
left
,
p
);
boolean
qLeft
=
find
(
root
.
left
,
q
);
if
(
pLeft
&&
qLeft
){
// 都在左子树
return
lowestCommonAncestor
(
root
.
left
,
p
,
q
);
}
else
if
(!
pLeft
&& !
qLeft
){
// 都在右子树
return
lowestCommonAncestor
(
root
.
right
,
p
,
q
);
}
else
{
// 一个在左子树,一个在右子树,则当前节点就是最近公共祖先。
return
root
;
}
}
// 检查 root这棵树中,是否有节点x
boolean
find
(
TreeNode
root
,
TreeNode
x
){
if
(
root
==
null
){
return
false
;
}
if
(
root
==
x
){
return
true
;
}
if
(
root
.
left
==
null
&&
root
.
right
==
null
){
return
false
;
}
else
if
(
root
.
left
==
null
&&
root
.
right
!=
null
){
return
find
(
root
.
right
,
x
);
}
else
if
(
root
.
left
!=
null
&&
root
.
right
==
null
){
return
find
(
root
.
left
,
x
);
}
else
{
return
find
(
root
.
left
,
x
) ||
find
(
root
.
right
,
x
);
}
}
}
Back
|
FazBrowse Home
|
New Git URL