1
class Solution {
2
public boolean isValidBST(TreeNode root) {
3
return dfs(root, Integer.MIN_VALUE, Integer.MAX_VALUE);
4
}
5

6
public boolean dfs(TreeNode root, int min, int max) {
7
if (root.val < min
8
|| root.val > max
9
|| (root.val == Integer.MIN_VALUE && root.left != null)
10
|| (root.val == Integer.MAX_VALUE && root.right != null)) return false;
11
boolean leftRight = true;
12
if (root.left == null && root.right == null) return true;
13
if (root.left != null) {
14
leftRight = dfs(root.left, min, root.val - 1);
15
}
16
if (root.right != null) {
17
leftRight = dfs(root.right, root.val + 1, max) && leftRight;
18
}
19
return leftRight;
20
}
21
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0