|
| 1 | +/** |
| 2 | + * Given a binary tree, determine if it is a valid Binary Search Tree (BST). |
| 3 | + */ |
| 4 | +public class ValidateBST { |
| 5 | + private static TreeNode previousVisitedNode; |
| 6 | + public static void main(String[] args){ |
| 7 | + System.out.println("Tree is valid = " + isValidBST(getValidTree())); |
| 8 | + System.out.println("Tree is valid = " + isValidBST(getInValidTree())); |
| 9 | + } |
| 10 | + |
| 11 | + public static class TreeNode { |
| 12 | + int val; |
| 13 | + TreeNode left; |
| 14 | + TreeNode right; |
| 15 | + TreeNode(int x) { val = x; } |
| 16 | + } |
| 17 | + |
| 18 | + public static TreeNode getValidTree(){ |
| 19 | + TreeNode root = new TreeNode(10); |
| 20 | + root.left = new TreeNode(5); |
| 21 | + root.right = new TreeNode(15); |
| 22 | + root.right.left = new TreeNode(13); |
| 23 | + root.right.right = new TreeNode(20); |
| 24 | + return root; |
| 25 | + } |
| 26 | + |
| 27 | + public static TreeNode getInValidTree(){ |
| 28 | + TreeNode root = new TreeNode(10); |
| 29 | + root.left = new TreeNode(5); |
| 30 | + root.right = new TreeNode(15); |
| 31 | + root.right.left = new TreeNode(6); |
| 32 | + root.right.right = new TreeNode(20); |
| 33 | + return root; |
| 34 | + } |
| 35 | + |
| 36 | + public static boolean isValidBST(TreeNode root) { |
| 37 | + return isInIncreasingOrder(root); |
| 38 | + } |
| 39 | + |
| 40 | + private static boolean isInIncreasingOrder(TreeNode root) { |
| 41 | + if(root == null) return true; |
| 42 | + |
| 43 | + if(isInIncreasingOrder(root.left)){ |
| 44 | + if(previousVisitedNode!=null && previousVisitedNode.val > root.val) return false; |
| 45 | + previousVisitedNode = root; |
| 46 | + return isInIncreasingOrder(root.right); |
| 47 | + } else { |
| 48 | + return false; |
| 49 | + } |
| 50 | + } |
| 51 | +} |
0 commit comments