Implementing a Generic Binary Tree in Java 2

The following two classes demonstrate an implementation of the Generic Binary Tree data structure.

The first class is BinaryTreeNode.java which acts as the node class for the tree, holding integer type data and two pointers for left and right child respectively of type same as the node class itself. The member fields are declared to be public by intention of increasing the readability of the code ahead.

The second class is GenericBinaryTree.java which provides the basic methods for creating and traversing the tree. So far, we’ve not added any method for deletion of nodes. The implementation provides two overloaded methods for inserting a new node in the tree.
First one is the raw level fill insertion, which inserts the new node on the first empty slot on last running level of the tree.
The other implementation provides option to tell the path of the new node to be inserted in the tree in the form of a String of consecutive ‘r’ and ‘l’ (small for ‘L’ char) characters to denote the two directions at each location starting from the root node. Note, however, that this method assumes that the root node has previously been created.

A sample class to demonstrate the usage of above code follows:

The sample usage code above makes a tree as shown below:

Binary Tree: as generated from the code

Binary Tree: as generated from the code

Rate this post

2 thoughts on “Implementing a Generic Binary Tree in Java

  1. Reply tom Sep 29,2017 10:10 pm

    What’s so generic in node tree (public int x) ???

    • Reply Anupam Jain Jan 12,2018 12:57 pm

      Hi Tom,

      By generic here we mean that the node structure itself is rather irrelevant. You could use any other node class instead of BinaryTreeNode as per your choice and the implementation strategy would still work.
      We are not referring to the Java Generics in anyway. Sorry if this is where you got confused.

      -Thanks
      Team Coddicted

Leave a Reply