Binary Tree Representation in Java

A Binary Tree in Java is represented as pointers connecting to each other in a hierarchical manner where a node can have two further reference pointers namely, a right child and a left child. The pointers point toward the value of the next pointing node.

Let’s understand through an illustration how we can represent a tree as pointers in Java:

If there is no left or right child of a particular node, the respective pointer will by default point to NULL.

In Java language, we represent a tree by creating a Class “Node” and then defining data for the node and left and right pointers for that node, hence initializing them using a constructor. In the main function, we can directly allocate memory dynamically using “new” keyword and assign further values to nodes as depicted by the pseudocode below.

Representation of a Tree through Pseudocode (Creating a Binary Tree):

Class Node{

// Defining value of the node.
int data;

// Left reference ptr to the node.
Node left;

// Right reference ptr to the node.
Node right;

// Constructor to initialize the above values.
Public Node (int val)
{
  data = val;
  left = right = NULL; 
}

};

main()
{
   // Creating a new node by using dynamic allocation in Java.
   Node root = new Node(1);
   root.left = new Node(2);
   root.right = new Node(3);
   root.left.right = new Node(5);

}

The tree created above would look something like this when drawn:

Special thanks to Priyanshi Goel for contributing to this article on takeUforward. If you also wish to share your knowledge with the takeUforward fam, please check out this article