Skip to content

Instantly share code, notes, and snippets.

@ethanjurman
Created May 11, 2018 20:22
Show Gist options
  • Save ethanjurman/145b792288dbf4fa16566db560d4e22f to your computer and use it in GitHub Desktop.
Save ethanjurman/145b792288dbf4fa16566db560d4e22f to your computer and use it in GitHub Desktop.
BT
// one class needs to have a main() method
public class HelloWorld
{
// arguments are passed using the text field below this editor
public static void main(String[] args)
{
Node<Integer> nodeA = new Node<>(1);
Node<Integer> nodeB = new Node<>(2);
Node<Integer> nodeC = new Node<>(3);
Node<Integer> nodeD = new Node<>(4);
Node<Integer> nodeE = new Node<>(5);
Node<Integer> nodeF = new Node<>(6);
Node<Integer> nodeG = new Node<>(7);
nodeA.insert(nodeB).insert(nodeC).insert(nodeD).insert(nodeE).insert(nodeF).insert(nodeG);
Node<Integer> nodeFound = nodeA.findNode(2);
System.out.println(nodeA.getString());
System.out.println(nodeA.getSize());
System.out.println(nodeFound.getString());
}
}
// you can add other public classes to this editor in any order
public class Node<T>
{
public Node<T> leftChild;
public Node<T> rightChild;
public T value;
public Node(T initialValue) {
value = initialValue;
}
public int getSize() {
int leftSize = leftChild != null ? leftChild.getSize() : 0;
int rightSize = rightChild != null ? rightChild.getSize() : 0;
return 1 + leftSize + rightSize;
}
public Node<T> insert(Node<T> node) {
if (leftChild == null) {
leftChild = node;
} else if (rightChild == null) {
rightChild = node;
} else if (leftChild.getSize() <= rightChild.getSize()) {
leftChild.insert(node);
} else {
rightChild.insert(node);
}
return this;
}
public Node<T> findNode(T searchValue) {
if (value == searchValue) {
return this;
}
if (leftChild != null) {
Node<T> leftSearch = leftChild.findNode(searchValue);
if (leftSearch != null) {
return leftSearch;
}
}
if (rightChild != null) {
Node<T> rightSearch = rightChild.findNode(searchValue);
if (rightSearch != null) {
return rightSearch;
}
}
return null;
}
public String getString() {
String leftString = leftChild != null ? leftChild.getString() : "";
String rightString = rightChild != null ? rightChild.getString() : "";
return "(" + leftString + " " + value + " " + rightString + ")";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment