diff --git a/BuildTree.java b/BuildTree.java new file mode 100644 index 00000000..10047e6a --- /dev/null +++ b/BuildTree.java @@ -0,0 +1,33 @@ +public class BuildTree { + private Map inorderMap = new HashMap<>(); + private int preorderIndex = 0; + // Time complexity: O(n) + // Space complexity: O(h) + // Ran on Leetcode: yes + public TreeNode buildTree(int[] preorder, int[] inorder) { + + for (int i = 0; i < inorder.length; i++) { + inorderMap.put(inorder[i], i); + } + + return helper(preorder, 0, inorder.length - 1); + } + + private TreeNode helper(int[] preorder, int left, int right) { + if (left > right) { + return null; + } + + int rootVal = preorder[preorderIndex]; + preorderIndex++; + TreeNode root = new TreeNode(rootVal); + + int inorderIndex = inorderMap.get(rootVal); + + root.left = helper(preorder, left, inorderIndex - 1); + + root.right = helper(preorder, inorderIndex + 1, right); + + return root; + } +} \ No newline at end of file diff --git a/ValidBST.java b/ValidBST.java new file mode 100644 index 00000000..30fe1297 --- /dev/null +++ b/ValidBST.java @@ -0,0 +1,16 @@ +class ValidBST { + // Time: O(n) + // Space: O(h) + // Ran on Leetcode: yes + public boolean isValidBST(TreeNode root) { + return helper(root, null, null); + } + + private boolean helper(TreeNode root, Integer min, Integer max) { + if(root == null ) return true; + if ((min != null && min >= root.val) || (max != null && max <= root.val)) { + return false; + } + return helper(root.left, min, root.val) && helper(root.right, root.val, max); + } +} \ No newline at end of file