Skip to content

Instantly share code, notes, and snippets.

@shah-smit
Created April 14, 2018 10:32
Show Gist options
  • Save shah-smit/5c49f8fbc94e2b3046324e8b63fc54ac to your computer and use it in GitHub Desktop.
Save shah-smit/5c49f8fbc94e2b3046324e8b63fc54ac to your computer and use it in GitHub Desktop.
Binary Search Tree
public class BST {
static TreeNode bst;
public static void main(String[] args){
bst = new TreeNode(10, new TreeNode(9), new TreeNode(11));
add(12);
add(1);
add(3);
System.out.println(bst);
remove(1);
System.out.println(bst);
}
public static void add(int i){
TreeNode t = bst;
while(t != null){
if(t.item > i){
if(t.left == null){
t.left = new TreeNode(i);
break;
}
else t = t.left;
}
if(t.item < i){
if(t.right == null){
t.right = new TreeNode(i);
break;
}
else t = t.right;
}
}
}
public static void remove(int i){
TreeNode t = bst;
while(t != null){
if(t.left != null && t.item == i){
t.left = null;
break;
}
if(t.right != null && t.item == i){
t.right = null;
break;
}
if(t != null && t.item > i){
t = t.left;
}
if(t != null && t.item < i){
t = t.right;
}
}
}
}
public class TreeNode {
TreeNode left;
TreeNode right;
int item;
TreeNode(int i){
item = i;
}
TreeNode(int i, TreeNode l, TreeNode r){
this(i);
left = l;
right = r;
}
@Override
public String toString(){
String returnString = "[ ";
if(left != null) returnString += "left: "+left.toString();
else returnString += "left: null";
returnString += " item: "+item;
if(right != null) returnString += " right: "+right.toString();
else returnString += " right: null";
returnString += " ]";
return returnString;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment