Binary Tree Data Structure in Java, easy in 5 minutes

This tutorial introduces a Binary Tree Data Structure in Java, both basic concept and its implementation in programming Java language. You know that one drawback of linked list is that data access is sequential and one of the disadvantages of using an array or linked list to store data is the time necessary to search for an item. Tree Data Structure is an improvement for that. Let’s learn and grow together.

Binary Tree Data Structure in Java

Tree Data Structure

A tree is a collection of nodes connected by directed (or undirected) edges. A tree is a nonlinear data structure, compared to arrays, linked lists, stacks and queues which are linear data structures. A tree can be empty with no nodes or a tree is a structure consisting of one node called the root and zero or one or more subtrees. A tree has following general properties.

Tree Data Structure
A Tree Data Structure

When we talk about tree, mostly we mean binary tree, that is a structure that has two children, left and right.

Binary Tree Representation

A tree whose elements have at most 2 children is called a binary tree. Since each element in a binary tree can have only 2 children, we typically name them the left and right child.

  • Data
  • Pointer to left child
  • Pointer to right child

Binary Tree Data Structure in Java

A pointer called ROOT points to the topmost node. Then the nodes that don’t have any children have their left and right pointers point to NULL.

We can represent a tree node in Java like this

Implementation of Binary Tree Data Structure

Now, you can try to implement a Binary Tree Data Structure in Java language like below.

Here is output when you run the above program

Applications of trees

  • Heap is a kind of tree that is used for heap sort.
  • Compilers use a syntax tree to validate the syntax of every program you write.
  • Manipulate hierarchical data.
  • Router algorithms
  • Manipulate hierarchical data.

References

Binary Tree Java Documentation

Please share it if you found this useful
Hide Buttons