Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions bstfromprepost.java
Original file line number Diff line number Diff line change
@@ -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<Integer, Integer> 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<Integer, Integer> 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;
}
}

31 changes: 31 additions & 0 deletions validateBST.java
Original file line number Diff line number Diff line change
@@ -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);
}
}