Created
April 25, 2017 17:41
-
-
Save peterkos/06c04e5f487c9e60490200f082b9e016 to your computer and use it in GitHub Desktop.
Binary tree with inorder traversal.
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
import static java.lang.System.*; | |
import java.util.ArrayList; | |
public class PCLegitBinaryTree { | |
public static void main(String[] args) { | |
/** | |
* BUILD THAT TREE! | |
* O | |
* /\ | |
* O O | |
* /\ | |
* O O | |
**/ | |
// Instantiate the root | |
Node<String> root = new Node<String>("I am root", null, null, null); | |
// Instantiate all the children | |
Node<String> childOne = new Node<String>("I am child one", root, null, null); | |
Node<String> childTwo = new Node<String>("I am child two", root, null, null); | |
Node<String> grandChildOne = new Node<String>("I am grandchild one", childOne, null, null); | |
Node<String> grandChildTwo = new Node<String>("I am grandchild two", childOne, null, null); | |
// You are the father! | |
// (Adds corresponding children to their parents.) | |
root.left = childOne; | |
root.right = childTwo; | |
childOne.left = grandChildOne; | |
childOne.rightChild = grandChildTwo; | |
// Inorder traversal | |
root.inorder(); | |
} | |
} | |
class Node<Element> { | |
public Element contents; | |
public Node<Element> parent; | |
public Node<Element> left; | |
public Node<Element> right; | |
// Basic contructor | |
public Node(Element contents, Node<Element> parent, Node<Element> left, Node<Element> right) { | |
this.contents = contents; | |
this.parent = parent; | |
this.left = left; | |
this.right = right; | |
} | |
// Inorder traversal | |
public void inorder() { | |
// Visit left subtree recursively | |
if (this.left != null) { | |
this.left.inorder(); | |
} | |
// Print out current contents | |
System.out.println(this.contents); | |
// Visit right subtree recursively | |
if (this.right != null) { | |
this.right.inorder(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment