Skip to content

Commit 61070a4

Browse files
committed
98.验证二叉搜索树
1 parent dd1d0fe commit 61070a4

File tree

3 files changed

+87
-0
lines changed

3 files changed

+87
-0
lines changed

leetcode_Java/DoneTitle.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@
5151
93. 复原 IP 地址
5252
94. 二叉树的中序遍历
5353
96. 不同的二叉搜索树
54+
98. 验证二叉搜索树
5455
101. 对称二叉树
5556
102. 二叉树的层序遍历
5657
103. 二叉树的锯齿形层序遍历

leetcode_Java/DoneType.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
一、树
1515
94. 二叉树的中序遍历
1616
96. 不同的二叉搜索树
17+
98. 验证二叉搜索树
1718
101. 对称二叉树
1819
102. 二叉树的层序遍历
1920
103. 二叉树的锯齿形层序遍历

leetcode_Java/Solution0098.java

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
// 98. 验证二叉搜索树
2+
3+
4+
/**
5+
* Definition for a binary tree node.
6+
* public class TreeNode {
7+
* int val;
8+
* TreeNode left;
9+
* TreeNode right;
10+
* TreeNode() {}
11+
* TreeNode(int val) { this.val = val; }
12+
* TreeNode(int val, TreeNode left, TreeNode right) {
13+
* this.val = val;
14+
* this.left = left;
15+
* this.right = right;
16+
* }
17+
* }
18+
*/
19+
20+
21+
class Solution {
22+
private long pre = Long.MIN_VALUE;
23+
24+
public boolean isValidBST(TreeNode root) {
25+
if (root == null) {
26+
return true;
27+
}
28+
if (!isValidBST(root.left)) {
29+
return false;
30+
}
31+
if (root.val <= pre) {
32+
return false;
33+
}
34+
pre = root.val;
35+
return isValidBST(root.right);
36+
}
37+
}
38+
39+
40+
class Solution {
41+
public boolean isValidBST(TreeNode root) {
42+
return isValid(root, null, null);
43+
}
44+
45+
private boolean isValid(TreeNode root, TreeNode min, TreeNode max) {
46+
if (root == null) {
47+
return true;
48+
}
49+
if (max != null && root.val >= max.val) {
50+
return false;
51+
}
52+
if (min != null && root.val <= min.val) {
53+
return false;
54+
}
55+
return isValid(root.left, min, root) && isValid(root.right, root, max);
56+
}
57+
}
58+
59+
60+
/*
61+
“94. 二叉树的中序遍历”,中序遍历存入列表,再遍历判断是否升序
62+
*/
63+
class Solution {
64+
public List<Integer> list = new ArrayList<>();
65+
66+
public boolean isValidBST(TreeNode root) {
67+
inorderTraversal(root);
68+
for (int i = 1; i < list.size(); i++) {
69+
if (list.get(i) <= list.get(i - 1)) {
70+
return false;
71+
}
72+
}
73+
return true;
74+
}
75+
76+
public List<Integer> inorderTraversal(TreeNode root) {
77+
if (root == null) {
78+
return list;
79+
}
80+
inorderTraversal(root.left);
81+
list.add(root.val);
82+
inorderTraversal(root.right);
83+
return list;
84+
}
85+
}

0 commit comments

Comments
 (0)