Skip to content

Instantly share code, notes, and snippets.

@shahzadaazam
Created December 23, 2020 07:48
Show Gist options
  • Save shahzadaazam/05e8386bd503a8c681afc9d7d3f54260 to your computer and use it in GitHub Desktop.
Save shahzadaazam/05e8386bd503a8c681afc9d7d3f54260 to your computer and use it in GitHub Desktop.
Custom implementation of a binary search tree
class Main {
public static void main(String[] args) {
TreeNode root = new TreeNode(5);
root.insert(1);
root.insert(3);
root.insert(7);
root.insert(9);
System.out.println(root.contains(2));
System.out.println(root.contains(3));
root.printInOrder();
}
}
class TreeNode {
int value;
TreeNode left;
TreeNode right;
public TreeNode() {
}
public TreeNode(int value) {
this.value = value;
}
public TreeNode(int value, TreeNode left, TreeNode right) {
this.value = value;
this.left = left;
this.right = right;
}
public void insert(int val) {
if (val <= value) {
if (left != null) {
left.insert(val);
} else {
left = new TreeNode(val);
}
} else {
if (right != null) {
right.insert(val);
} else {
right = new TreeNode(val);
}
}
}
public boolean contains(int val) {
if (val == value) {
return true;
} else if (val < value) {
if (left != null) {
return left.contains(val);
} else {
return false;
}
} else {
if (right != null) {
return right.contains(val);
} else {
return false;
}
}
}
public void printInOrder() {
if (left != null) {
left.printInOrder();
}
System.out.println(value);
if (right != null) {
right.printInOrder();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment