diff --git a/BinaryTreePreOrderInOrderTraversal.java b/BinaryTreePreOrderInOrderTraversal.java new file mode 100644 index 00000000..91878aa7 --- /dev/null +++ b/BinaryTreePreOrderInOrderTraversal.java @@ -0,0 +1,31 @@ + +//Time Complexity : O(n2) +//Space Complexity: O(1) +class BinaryTreePreOrderInOrderTraversal { + public TreeNode buildTree(int[] preorder, int[] inorder) + { + //PreOrder - root, left, right + //InOrder - left, root, right + if(preorder.length == 0) return null; + int idx = -1; + int rootVal = preorder[0]; // first element in preOrder is nothing but root + TreeNode root = new TreeNode(rootVal); + + //Finding the index of the root value in the inorder array + for(int i = 0; i < inorder.length; i++){ + if(inorder[i] == rootVal){ + idx = i; + break; + } + } + + int[] preLeft = Arrays.copyOfRange(preorder, 1, idx+1); + int[] preRight = Arrays.copyOfRange(preorder, idx+1, preorder.length); + int[] inLeft = Arrays.copyOfRange(inorder, 0, idx); + int[] inRight = Arrays.copyOfRange(inorder, idx+1, inorder.length); + + root.left = buildTree(preLeft, inLeft); + root.right = buildTree(preRight, inRight); + return root; + } +} \ No newline at end of file diff --git a/ValidBST.java b/ValidBST.java new file mode 100644 index 00000000..b95a3042 --- /dev/null +++ b/ValidBST.java @@ -0,0 +1,46 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode() {} + * TreeNode(int val) { this.val = val; } + * TreeNode(int val, TreeNode left, TreeNode right) { + * this.val = val; + * this.left = left; + * this.right = right; + * } + * } + */ + +//Time Complexity : O(n) +//Space Complexity: O(h) for skewed where 'h' is the height of the tree +//Space Complexity: O(log n) for non-skewed +class ValidBST { + + // Initialize global variables + boolean isValidBST = true; + TreeNode prev = null; + + public boolean isValidBST(TreeNode root) { + helper(root); + return isValidBST; + } + + private void helper(TreeNode root) + { + //Base case + if(root == null) return; + + helper(root.left); + + // Check if current root value is less than or equal to previous root value + if (prev != null && prev.val >= root.val){ + isValidBST = false; + } + prev = root; + + helper(root.right); + } +} \ No newline at end of file