-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path98_Validate_Binary_Search_Tree.java
More file actions
40 lines (39 loc) · 1.2 KB
/
98_Validate_Binary_Search_Tree.java
File metadata and controls
40 lines (39 loc) · 1.2 KB
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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isValidBST(TreeNode root) {
return isChildValidBST(root, null, null);
}
boolean isChildValidBST(TreeNode root, Integer lowerBound, Integer upperBound) {
boolean left = true;
boolean right = true;
if (root.left != null) {
if (root.left.val >= root.val || (lowerBound != null && root.left.val <= lowerBound)) {
left = false;
} else {
left = isChildValidBST(root.left, lowerBound, root.val);
}
}
if (root.right != null) {
if (root.right.val <= root.val || (upperBound != null && root.right.val >= upperBound)) {
right = false;
} else {
right = isChildValidBST(root.right, root.val, upperBound);
}
}
return left && right;
}
}