diff --git a/bstfromprepost.java b/bstfromprepost.java new file mode 100644 index 00000000..15748e2d --- /dev/null +++ b/bstfromprepost.java @@ -0,0 +1,36 @@ +// Time Complexity : O(n) where n is the number of nodes in the tree +// Space Complexity : O(n) where n is the number of nodes in the tree +// Did this code successfully run on Leetcode : yes +// Any problem you faced while coding this : problem in keeping track of the index of the preorder array and making the recursive function to build the tree +// Your code here along with comments explaining your approach : hash map to store index of inorder array to get the index of root in O(1) time. Using preorder array to get the root value and then using the index from hash map to divide the inorder array into left and right subtrees. Recursively building the left and right subtrees. + +class Solution { + + int idx; + public TreeNode buildTree(int[] preorder, int[] inorder) { + HashMap map = new HashMap<>(); + for(int i = 0; i < inorder.length; i++){ + map.put(inorder[i], i); + } + this.idx = 0; + return helper(preorder, 0, preorder.length - 1, map); + } + + private TreeNode helper(int[] preorder, int start, int end, HashMap map){ + + if(start > end) return null; + + int rootVal = preorder[idx]; + idx++; + + int rootIdx = map.get(rootVal); + + TreeNode root = new TreeNode(rootVal); + + root.left = helper(preorder, start, rootIdx - 1, map); + root.right = helper(preorder, rootIdx + 1, end, map); + + return root; + } +} + diff --git a/validateBST.java b/validateBST.java new file mode 100644 index 00000000..5fe08572 --- /dev/null +++ b/validateBST.java @@ -0,0 +1,31 @@ +// Time Complexity : O(n) where n is the number of nodes in the tree +// Space Complexity : O(h) where h is the height of the tree +// Did this code successfully run on Leetcode : yes +// Any problem you faced while coding this : only little in making the recursive function and keeping track of the previous node + +// Your code here along with comments explaining your approach: flag is used to keep track of whether the tree is a valid BST or not. prev is used to keep track of the previous node in the inorder traversal. Inorder traversal of a BST should give us a sorted sequence of values. So, we can compare the current node's value with the previous node's value to check if the BST property is violated. + +class Solution { + boolean flag; + TreeNode prev; + + public boolean isValidBST(TreeNode root) { + this.flag = true; + helper(root); + return flag; + } + + private void helper(TreeNode root){ + if(root == null) return; + + helper(root.left); + + if(prev != null && prev.val >= root.val){ + flag = false; + } + + prev = root; + helper(root.right); + } +} +