diff --git a/preorder_inorder_contruct_tree.java b/preorder_inorder_contruct_tree.java new file mode 100644 index 00000000..caab4121 --- /dev/null +++ b/preorder_inorder_contruct_tree.java @@ -0,0 +1,53 @@ +// class Solution { +// public TreeNode buildTree(int[] preorder, int[] inorder) { +// if(preorder.length==0) return null; + +// int rootVal = preorder[0]; +// int rootIdx = -1; + +// for(int i=0;i map = new HashMap<>(); + for(int i=0; i map){ + //base + if(st>end) return null; //--> this works because we need null in cases the values are missing + //logic + int rootVal = preorder[idx];// preoder is a parameter bcs we need the root val + idx++; // ids is global bcs it stricitly increases + TreeNode root= new TreeNode(rootVal); + int rootIdx= map.get(rootVal); + //left + root.left = helper(preorder,st, rootIdx-1,map); // we keep the start the same as in the inital and then move + root.right = helper(preorder,rootIdx+1,end,map); + return root; + } +} \ No newline at end of file diff --git a/validate_bst.java b/validate_bst.java new file mode 100644 index 00000000..543e4103 --- /dev/null +++ b/validate_bst.java @@ -0,0 +1,29 @@ +// time complexity = 0(n) n- number of nodes in the tree +// space complexity = o(h) h - height of the tree +// we use condition recursion, it checks if the left is smaller to the root value, if yes then only moves and checks for right value, cutting the time down as soon as we encounter an issue. + +class Solution { + TreeNode prev; + // boolean flag; + public boolean isValidBST(TreeNode root) { + return helper(root); + } + private boolean helper(TreeNode root){ + // base case + if (root == null) return true; + + // left + boolean left = helper(root.left); + if(prev!=null && root.val<=prev.val){ + return false; + } + this.prev = root; + // right + boolean right = true; + if(left){ + right =helper(root.right); //conditional recursion + } + return left && right; + + } +} \ No newline at end of file