-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_0098ValidateBinarySearchTree.java
More file actions
36 lines (32 loc) · 1.05 KB
/
_0098ValidateBinarySearchTree.java
File metadata and controls
36 lines (32 loc) · 1.05 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
package com.heatwave.leetcode.problems;
public class _0098ValidateBinarySearchTree {
class Solution {
long num = Long.MIN_VALUE;
public boolean isValidBST(TreeNode root) {
if (root == null) {
return true;
}
boolean leftIsValid = isValidBST(root.left);
if (root.val <= num) {
return false;
}
num = root.val;
boolean rightIsValid = isValidBST(root.right);
return leftIsValid && rightIsValid;
}
}
class AnotherSolution {
public boolean isValidBST(TreeNode root) {
return helper(root, Long.MIN_VALUE, Long.MAX_VALUE);
}
private boolean helper(TreeNode root, long lower, long upper) {
if (root == null) {
return true;
}
if (root.val <= lower || root.val >= upper) {
return false;
}
return helper(root.left, lower, root.val) && helper(root.right, root.val, upper);
}
}
}