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