Skip to content

Instantly share code, notes, and snippets.

@peterkos
Created April 25, 2017 17:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save peterkos/06c04e5f487c9e60490200f082b9e016 to your computer and use it in GitHub Desktop.
Save peterkos/06c04e5f487c9e60490200f082b9e016 to your computer and use it in GitHub Desktop.
Binary tree with inorder traversal.
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