FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
leetcode/code/lc98.java at master · mJackie/leetcode · GitHub
mJackie
/
leetcode
Public
Notifications
You must be signed in to change notification settings
Fork
135
Star
405
Code
Issues
0
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
leetcode
/
code
/
lc98.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
54 lines (52 loc) · 1.86 KB
Breadcrumbs
leetcode
/
code
/
lc98.java
Copy path
File metadata and controls
54 lines (52 loc) · 1.86 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
package
code
;
/*
* 98. Validate Binary Search Tree
* 题意:判断是否为二叉搜索树
* 难度:Medium
* 分类:Tree, Depth-first Search
* 思路:两种方法,一种递归;另一种中序遍历的思路;
* Tips:递归时注意设置最大最小两个参数,因为节点间val限制会传递的
*/
import
java
.
util
.
Stack
;
public
class
lc98
{
public
static
void
main
(
String
[]
args
) {
TreeNode
tn1
=
new
TreeNode
(
0
);
tn1
.
left
=
new
TreeNode
(-
1
);
//System.out.println(isValidBST(tn1));
System
.
out
.
println
(
isValidBST2
(
tn1
));
}
public
static
class
TreeNode
{
int
val
;
TreeNode
left
;
TreeNode
right
;
TreeNode
(
int
x
) {
val
=
x
; }
}
public
static
boolean
isValidBST
(
TreeNode
root
) {
if
(
root
==
null
)
return
true
;
return
dfs
(
root
, -
Double
.
MAX_VALUE
,
Double
.
MAX_VALUE
);
// 注意Double.MIN_VALUE是接近0的正数
}
public
static
boolean
dfs
(
TreeNode
root
,
double
min_bound
,
double
max_bound
){
//设置两个参数,一个最大值,一个最小值
if
(
root
==
null
)
return
true
;
if
(
root
.
val
>=
max_bound
||
root
.
val
<=
min_bound
)
return
false
;
return
dfs
(
root
.
left
,
min_bound
,
root
.
val
) &&
dfs
(
root
.
right
,
root
.
val
,
max_bound
);
}
public
static
boolean
isValidBST2
(
TreeNode
root
) {
if
(
root
==
null
)
return
true
;
Stack
<
TreeNode
>
st
=
new
Stack
();
TreeNode
pre
=
null
;
while
( !
st
.
isEmpty
() ||
root
!=
null
){
while
(
root
!=
null
){
st
.
add
(
root
);
root
=
root
.
left
;
}
root
=
st
.
pop
();
if
(
pre
!=
null
&&
root
.
val
<=
pre
.
val
)
//先序遍历,自下而上,孩子节点小于父节点
return
false
;
pre
=
root
;
root
=
root
.
right
;
}
return
true
;
}
}
Back
|
FazBrowse Home
|
New Git URL