|
1 | 1 | package com.pulkit.datastructures_algorithms.done.trees;
|
2 | 2 |
|
| 3 | + |
| 4 | +//TODO: Optimize it more, no need for too much recursuve calls |
3 | 5 | public class CheckIfValidBST {
|
4 | 6 | public static void main(String[] args) {
|
5 | 7 | TreeNode root = createBST();
|
6 | 8 | System.out.println(isValidBST(root));
|
| 9 | + |
| 10 | + TreeNode anotherRoot = createBST(); |
| 11 | + System.out.println(isValidBSTV2(anotherRoot, null, null)); |
7 | 12 | }
|
8 | 13 |
|
9 |
| - public static boolean isValidBST(TreeNode node) { |
| 14 | + static boolean isValidBST(TreeNode node) { |
10 | 15 | if (node == null)
|
11 | 16 | return true;
|
12 | 17 |
|
@@ -49,6 +54,29 @@ private static Integer findMax(TreeNode node) {
|
49 | 54 | return Math.max(node.data, Math.max(maxInLeftSubtree, maxInRightSubtree));
|
50 | 55 | }
|
51 | 56 |
|
| 57 | + static boolean isValidBSTV2(TreeNode node, Integer max, Integer min) { |
| 58 | + if (node == null) { |
| 59 | + return true; |
| 60 | + } |
| 61 | + |
| 62 | + if ((max != null && node.data > max) || (min != null && node.data < min)) { |
| 63 | + return false; |
| 64 | + } |
| 65 | + |
| 66 | + boolean isLeftSubtreeValid = isValidBSTV2(node.leftChild, node.data, min); |
| 67 | + boolean isRightSubtreeValid = isValidBSTV2(node.rightChild, max, node.data); |
| 68 | + |
| 69 | + if (!isLeftSubtreeValid || !isRightSubtreeValid) { |
| 70 | + return false; |
| 71 | + } |
| 72 | + return true; |
| 73 | + |
| 74 | + /* |
| 75 | + simplified version |
| 76 | + return isLeftSubtreeValid && isRightSubtreeValid; |
| 77 | + */ |
| 78 | + } |
| 79 | + |
52 | 80 | public static TreeNode createBST() {
|
53 | 81 | TreeNode fourteen = new TreeNode(14, null, null);
|
54 | 82 | TreeNode six = new TreeNode(6, null, null);
|
|
0 commit comments