Created
May 11, 2018 20:22
-
-
Save ethanjurman/145b792288dbf4fa16566db560d4e22f to your computer and use it in GitHub Desktop.
BT
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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