Javatpoint Logo
Javatpoint Logo

Binary Tree Java

Binary tree is a tree type non-linear data structure that are mainly used for sorting and searching because they store data in hierarchical form. In this section, we will learn the implementation of binary tree data structure in Java. Also, provides a short description of binary tree data structure.

Binary Tree

A tree in which each node (parent) has at most two-child nodes (left and right) is called binary tree. The top most node is called the root node. In a binary tree a node contains the data and the pointer (address) of the left and right child node.

The height of a binary tree is the number of edges between the tree's root and its furthest (deepest) leaf. If the tree is empty, the height is 0. The height of the node is denoted by h.

Binary Tree Java

The height of the above binary tree is 2.

We can calculate the number of leaves and node by using the following formula.

  • Maximum number of leaf nodes is a binary tree: 2h
  • Maximum number of nodes is a binary tree: 2h+1-1

Where, h is the height of binary tree.

Example of Binary Tree

Binary Tree Java

Types of Binary Tree

There are the following types of binary tree in data structure:

  1. Full/ Strictly Binary Tree
  2. Complete Binary Tree
  3. Perfect Binary Tree
  4. Balance Binary Tree
  5. Rooted Binary Tree
  6. Degenerated/ Pathological Binary Tree
  7. Extended Binary Tree
  8. Skewed Binary Tree
    1. Left-skewed Binary Tree
    2. Right-skewed Binary Tree
  9. Threaded Binary Tree
    1. Single Threaded Binary Tree
    2. Double Threaded Binary Tree

Binary Tree Implementation in Java

There are many ways to implement binary tree. In this section, we will implement binary tree using LinkedList data structure. Along with it, we will also implement the traversal orders, searching a node and insert a node in a binary tree.

Implementation of Binary Tree Using LinkedList

Algorithm

Define Node class that contains three attributes namely: data left and right. Here, left represents the left child of the node and right represents the right child of the node.

  • When a node is created, data will pass to data attribute of the node and both left and right will be set to null.
  • Define another class that has an attribute root.
  • Root represents the root node of the tree and initialize it to null.
  1. insert() will add a new node to the tree:
    • It checks whether the root is null, which means the tree is empty. It will add the new node as root.
    • Else, it will add root to the queue.
    • The variable node represents the current node.
    • First, it checks whether a node has a left and right child. If yes, it will add both nodes to queue.
    • If the left child is not present, it will add the new node as the left child.
    • If the left is present, then it will add the new node as the right child.
  2. inorder() will display nodes of the tree in inorder fashion.
    • It traverses the entire tree then prints out left child followed by root then followed by the right child.

BinarySearchTree.java

Output:

Binary tree after insertion
1 
Binary tree after insertion
2 1 3 
Binary tree after insertion
4 2 5 1 3 
Binary tree after insertion
4 2 5 1 6 3 7

Binary Tree Operations

The following operations can be performed on a binary tree:

  • Insertion
  • Deletion
  • Search
  • Traversal

Java Program to Insert a Node in Binary Tree

BinaryTreeInsert.java

Output:

Building tree with root value 25
=================================
  Inserted 11 to left of Node 25
  Inserted 15 to right of Node 11
  Inserted 16 to right of Node 15
  Inserted 23 to right of Node 16
  Inserted 79 to right of Node 25

Java Program to Delete a Node in Java

Algorithm

  1. Starting at the root, find the deepest and rightmost node in binary tree and node that we want to delete.
  2. Replace the deepest rightmost node's data with the node to be deleted.
  3. Then delete the deepest rightmost node.

Consider the following figure.

Binary Tree Java

DeleteNode.java

Output:

Inorder traversal before deletion: 7 11 12 10 15 9 8 
Inorder traversal after deletion: 8 11 12 10 15 9 

Java Program to Search a Node in Binary Tree

Algorithm

  • Define Node class which has three attributes namely: data left and right. Here, left represents the left child of the node and right represents the right child of the node.
  • When a node is created, data will pass to data attribute of the node and both left and right will be set to null.
  • Define another class which has two attribute root and flag.
    1. Root represents the root node of the tree and initializes it to null.
    2. The Flag will be used to check whether the given node is present in the tree or not. Initially, it will be set to false.
  1. searchNode() will search for a particular node in the binary tree:
    • It checks whether the root is null, which means the tree is empty.
    • If the tree is not empty, it will compare temp's data with value. If they are equal, it will set the flag to true and return.
    • Traverse left subtree by calling searchNode() recursively and check whether the value is present in left subtree.
    • Traverse right subtree by calling searchNode() recursively and check whether the value is present in the right subtree.

SearchBinaryTree.java

Output:

Element is present in the binary tree.

Binary Tree Traversal

Traversal Order First Visit Second Visit Third Visit
Inorder Visit left subtree in inorder Visit root node Visit right subtree in inorder
Preorder Visit root node Visit left subtree in preorder Visit right subtree in preorder
Postorder Visit left subtree in postorder Visit right subtree in postorder Visit root node

Note: Except the above three traversals, there is another traversal order is called boundary traversal.

Java Program to Traverse Inorder, Preorder, and Postorder Traversal

BinaryTree.java

Output:

Inorder traversal of binary tree
12 34 56 67 89 90 
Preorder traversal of binary tree
34 12 56 89 67 90 
Postorder traversal of binary tree
12 67 90 89 56 34

Besides the above operations, we can also perform the operations such as large node, smallest node, and sum of all nodes.

Java Program to Find the Largest Node in Binary Tree

LargestNode.java

Output:

Largest element in the binary tree: 99

Java Program to Find the Smallest Node in Binary Tree

Algorithm

  1. Define Node class which has three attributes namely: data, left and right. Here, left represents the left child of the node and right represents the right child of the node.
  2. When a node is created, data will pass to data attribute of node and both left and right will be set to null.
  3. Define another class which has an attribute root.
    1. Rootrepresent root node of the tree and initialize it to null.
  1. smallestElement() will find out the smallest node in binary tree:
    1. It checks whether root is null, which means tree is empty.
    2. If tree is not empty, define a variable min that will store temp's data.
    3. Find out the minimum node in left subtree by calling smallestElement() recursively. Store that value in leftMin. Compare the value of min with leftMin and store the minimum of two to min.
    4. Find out the minimum node in right subtree by calling smallestElement() recursively. Store that value in rightMin. Compare the value of min with rightMin and store the maximum of two to min.
    5. At the end, min will hold the smallest node in the binary tree.

SmallestNode.java

Output:

Smallest element in the binary tree: 1

Java Program to Find the Maximum Width of a Binary Tree

Algorithm

  1. Define Node class which has three attributes namely: data left and right. Here, left represents the left child of the node and right represents the right child of the node.
  2. When a node is created, data will pass to data attribute of the node and both left and right will be set to null.
  3. Define another class which has an attribute root.
    1. Root represents the root node of the tree and initializes it to null.
  4. findMaximumWidth() will find out the maximum width of the given binary tree:
    1. Variable maxWidth will store the maximum number of nodes present in any level.
    2. The queue is used for traversing binary tree level-wise.
    3. It checks whether the root is null, which means the tree is empty.
    4. If not, add the root node to queue. Variable nodesInLevel keeps track of the number of nodes in each level.
    5. If nodesInLevel > 0, remove the node from the front of the queue and add its left and right child to the queue. For the first iteration, node 1 will be removed and its children nodes 2 and 3 will be added to the queue. In the second iteration, node 2 will be removed, its children 4 and 5 will be added to the queue and so on.
    6. MaxWidth will store max(maxWidth, nodesInLevel). So, at any given point of time, it will represent the maximum number of nodes.
    7. This will continue till all the levels of the tree is traversed.

BinaryTree.java

Output:

Maximum width of the binary tree: 4






Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA