FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
JavaArithmetic/src/LeetCode/LeetCode253.java at master · wpq2014/JavaArithmetic · GitHub
wpq2014
JavaArithmetic
Repository navigation
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
JavaArithmetic
/
src
/
LeetCode
/
LeetCode253.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
45 lines (32 loc) · 1.22 KB
Breadcrumbs
JavaArithmetic
/
src
/
LeetCode
/
LeetCode253.java
Copy path
File metadata and controls
45 lines (32 loc) · 1.22 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
package
LeetCode
;
public
class
LeetCode253
{
/// 235. Lowest Common Ancestor of a Binary Search Tree
/// https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/description/
/// 时间复杂度: O(lgn), 其中n为树的节点个数
/// 空间复杂度: O(h), 其中h为树的高度
// Definition for a binary tree node.
public
class
TreeNode
{
int
val
;
TreeNode
left
;
TreeNode
right
;
TreeNode
(
int
x
) {
val
=
x
;
}
}
public
TreeNode
lowestCommonAncestor
(
TreeNode
root
,
TreeNode
p
,
TreeNode
q
) {
if
(
p
==
null
||
q
==
null
)
throw
new
IllegalArgumentException
(
"p or q can not be null."
);
if
(
root
==
null
)
return
null
;
// p q 都在root左边
if
(
p
.
val
<
root
.
val
&&
q
.
val
<
root
.
val
)
return
lowestCommonAncestor
(
root
.
left
,
p
,
q
);
// p q 都在root右边
if
(
p
.
val
>
root
.
val
&&
q
.
val
>
root
.
val
)
return
lowestCommonAncestor
(
root
.
right
,
p
,
q
);
assert
p
.
val
==
root
.
val
||
q
.
val
==
root
.
val
|| (
root
.
val
-
p
.
val
) * (
root
.
val
-
q
.
val
) <
0
;
// 某个节点是root,直接返回root
return
root
;
}
}
Back
|
FazBrowse Home
|
New Git URL