Skip to content

Commit 46b9086

Browse files
committed
add leetcode: 98
1 parent 2680bfd commit 46b9086

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
package leetCode.subject.number51_100;
2+
3+
/**
4+
* @author : CodeWater
5+
* @create :2022-08-15-22:25
6+
* @Function Description :98. 验证二叉搜索树
7+
*/
8+
public class _98VerifyBinarySearchTree {
9+
/**
10+
* Definition for a binary tree node.
11+
* public class TreeNode {
12+
* int val;
13+
* TreeNode left;
14+
* TreeNode right;
15+
* TreeNode() {}
16+
* TreeNode(int val) { this.val = val; }
17+
* TreeNode(int val, TreeNode left, TreeNode right) {
18+
* this.val = val;
19+
* this.left = left;
20+
* this.right = right;
21+
* }
22+
* }
23+
*/
24+
class Solution {
25+
/**按照定义来判断:
26+
左子树小于根,右子树大于根
27+
*/
28+
public boolean isValidBST(TreeNode root) {
29+
// 空树也是一个二叉搜索树
30+
if( root == null ) return true;
31+
// 看第一个元素是不是1,是1没问题,不是1有问题
32+
return dfs( root )[0] == 1 ;
33+
34+
}
35+
36+
int[] dfs( TreeNode root ){
37+
/**
38+
res数组有三个元素:res[0]=0表示有问题,res[0]=1表示没有问题;
39+
res[1]表示这个子树中的最小值
40+
res[2]表示这个子树中的最大值
41+
空树判断在另外一个函数中判断了,这里就不判断了
42+
*/
43+
int[] res = { 1 , root.val , root.val };
44+
// 存在左子树
45+
if( root.left != null ){
46+
// t暂存左子树
47+
int[] t = dfs( root.left );
48+
// 左子树有问题或者左子树的最大值大于根,说明这不是二叉搜索树,res[0]置0表示有问题
49+
if( t[0] == 0 || t[2] >= root.val )res[0] = 0;
50+
// 同时更新res中最小值和最大值
51+
res[1] = Math.min( res[1] , t[1] );
52+
res[2] = Math.max( res[2] , t[2] );
53+
54+
}
55+
// 存在右子树(同理)
56+
if( root.right != null ){
57+
int[] t = dfs( root.right );
58+
if( t[0] == 0 || t[1] <= root.val ) res[0] = 0;
59+
res[1] = Math.min( res[1] , t[1] );
60+
res[2] = Math.max( res[2] , t[2] );
61+
}
62+
63+
return res;
64+
}
65+
}
66+
}

0 commit comments

Comments
 (0)