Skip to content

Instantly share code, notes, and snippets.

@dekaikiwi
Created January 4, 2019 10:08
Show Gist options
  • Save dekaikiwi/569e32f0beae50590f965a0325eefbce to your computer and use it in GitHub Desktop.
Save dekaikiwi/569e32f0beae50590f965a0325eefbce to your computer and use it in GitHub Desktop.
Implementation of a Binary Search Tree in Java
package jono.structures;
import java.util.stream.Stream;
import jono.structures.Node;
public class Bst {
public static void main(String args[]) {
Node root = null;
int[] numbers = Stream.of(args[0].split(",")).mapToInt(Integer::parseInt).toArray();
for(int i = 0; i < numbers.length; i++) {
int number = numbers[i];
if (root == null) {
root = new Node(number);
} else {
root.insert(number);
}
}
System.out.println("== IN ORDER ==");
root.inOrder();
System.out.println("== PRE ORDER ==");
root.preOrder();
System.out.println("== POST ORDER ==");
root.postOrder();
System.out.println("Contains 3: " + root.contains(3));
System.out.println("Contains 1000: " + root.contains(1000));
}
}
package jono.structures;
public class Node {
Node left, right;
int value;
public Node(int value) {
this.value = value;
}
public void insert(int value) {
if (this.value > value) {
if (this.left == null) {
this.left = new Node(value);
} else {
this.left.insert(value);
}
} else {
if (this.right == null) {
this.right = new Node(value);
} else {
this.right.insert(value);
}
}
}
public boolean contains(int value) {
if (this.value == value) { return true; }
if (this.value > value) {
if (this.left != null) {
return this.left.contains(value);
}
} else {
if (this.right != null) {
return this.right.contains(value);
}
}
return false;
}
public void inOrder() {
if (this.left != null) { this.left.inOrder(); }
System.out.println(this.value);
if (this.right != null) { this.right.inOrder(); }
}
public void preOrder() {
System.out.println(this.value);
if (this.left != null) { this.left.preOrder(); }
if (this.right != null) { this.right.preOrder(); }
}
public void postOrder() {
if (this.left != null) { this.left.preOrder(); }
if (this.right != null) { this.right.preOrder(); }
System.out.println(this.value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment