|
26 | 26 | Binary tree [1,2,3], return false.
|
27 | 27 | */
|
28 | 28 | public class _98 {
|
29 |
| - class MoreConciseSolution { |
| 29 | + |
| 30 | + public static class Solution1 { |
30 | 31 |
|
31 | 32 | public boolean isValidBST(TreeNode root) {
|
32 | 33 | return valid(root, null, null);
|
33 | 34 | }
|
34 | 35 |
|
35 |
| - private boolean valid(TreeNode root, Integer min, Integer max) { |
36 |
| - if (root == null) return true; |
37 |
| - if ((min != null && root.val <= min) |
38 |
| - || (max != null && root.val >= max)) return false; |
| 36 | + boolean valid(TreeNode root, Integer min, Integer max) { |
| 37 | + if (root == null) { |
| 38 | + return true; |
| 39 | + } |
| 40 | + if ((min != null && root.val <= min) || (max != null && root.val >= max)) { |
| 41 | + return false; |
| 42 | + } |
39 | 43 | return valid(root.left, min, root.val) && valid(root.right, root.val, max);
|
40 | 44 | }
|
41 | 45 | }
|
42 | 46 |
|
43 | 47 |
|
44 |
| - public boolean isValidBST(TreeNode root) { |
45 |
| - if (root == null) return true; |
46 |
| - return dfs(root.left, Long.MIN_VALUE, root.val) && dfs(root.right, root.val, Long.MAX_VALUE); |
47 |
| - } |
| 48 | + public static class Solution2 { |
| 49 | + public boolean isValidBST(TreeNode root) { |
| 50 | + if (root == null) return true; |
| 51 | + return dfs(root.left, Long.MIN_VALUE, root.val) && dfs(root.right, root.val, Long.MAX_VALUE); |
| 52 | + } |
48 | 53 |
|
49 |
| - private boolean dfs(TreeNode root, long minValue, long maxValue) { |
50 |
| - if (root == null) return true; |
51 |
| - if (root != null && (root.val <= minValue || root.val >= maxValue)) return false; |
52 |
| - boolean leftResult = true, rightResult = true; |
53 |
| - if (root.left != null) leftResult = dfs(root.left, minValue, root.val); |
54 |
| - if (root.right != null) rightResult = dfs(root.right, root.val, maxValue); |
55 |
| - return leftResult && rightResult; |
| 54 | + private boolean dfs(TreeNode root, long minValue, long maxValue) { |
| 55 | + if (root == null) return true; |
| 56 | + if (root != null && (root.val <= minValue || root.val >= maxValue)) return false; |
| 57 | + boolean leftResult = true, rightResult = true; |
| 58 | + if (root.left != null) leftResult = dfs(root.left, minValue, root.val); |
| 59 | + if (root.right != null) rightResult = dfs(root.right, root.val, maxValue); |
| 60 | + return leftResult && rightResult; |
| 61 | + } |
56 | 62 | }
|
57 | 63 |
|
58 |
| - public static void main(String... args) { |
59 |
| - System.out.println(Integer.MAX_VALUE == 2147483647); |
60 |
| - } |
61 | 64 | }
|
0 commit comments