Implementing a Generic Binary Tree in Java - Coddicted

Implementing a Generic Binary Tree in Java

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

The first class is 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 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

Back To Top
Rate this post

Leave a Reply