Generic Binary Tree implementation in Java

Călin Gabriel
2 min readJun 30, 2015

--

In the following tutorial I’m going to implement a core data structure, widely used in computing called the Binary Tree. Attention! This is not the Binary Search Tree.

To add a little fun to it, I’m gonna also write a little dog genealogy app that lets you build a tree hierarchy of the greatest dogs and their breeds throughout dog-kind.

Great, let’s begin.

So, the first thing I asked myself was — how do the two tree types differ ? Simple. The search tree inserts new data by a very specific rule:

If you didn’t figure it out already : smaller goes left, bigger goes right.

Our simple binary tree, however. Does not necessarily obey to this rule.

Let’s begin the implementation. First, we want to model the data structures.

TElem is the terminology I’ll be using for a generic data type. ( It can be anything: integer, string, float, custom defined class .. )

As you can see, the code is pretty straightforward. The data is encapsulated in a leaf. To link a child, you create a new binary tree and bind it to a existing binary tree.

As for the iterator, I am using the preorder. You can write your own iterator by implementing Iterator<BinaryTree<T>> and return it on our iterator() method. As you can see, we respect the open-closed principle.

Great, now let’s write some tests to make sure everything acts as it’s supposed to do using jUnit 4.

Run it and voila, all things working fine. Now we have the data structure up and running. Let’s move on to our doggie app.

I don’t wanna mix logic with view so I’ll just use a controller class to be the intermediate. This way if I change my mind later and I want for example to scale my dog app to the web, I’ll have a much better time, given that only the view class needs to change. This way we respect the SRP ( Single Reponsability Principle ).

You can see on line 37 the ChildrenOccupiedException. That happens when both the left and right spots are occupied, we’ll need to catch that exception later in the UI layer.

Cool, now let’s just call the UI from our main function.

Run it and enjoy your own dog hierarchy app.

--

--