How to find the Smallest element in binary tree in Java

In this program, we will search for the smallest element in the binary tree. Here, we have traversed the tree for searching the number. There are many steps are included to find the Smallest element in a binary tree in Java.

  1. Initialize the variables
  2. Traverse the left subtree
  3. Store the minimum value of the left subtree
  4. Traverse the right subtree
  5. Find the minimum number
  6. Compare with a minimum value of left subtree

Java program to find the smallest element in a binary tree

public class SN {  
      public static class Node{  
        int data;  
        Node left;  
        Node right;  
        public Node(int data){  
            this.data = data;  
            this.left = null;  
            this.right = null;  
        }  
      }  
      public Node root;  
      public SN(){  
          root = null;  
      }    
      public int smallestElement(Node temp){  
          if(root == null) {  
              System.out.println("Tree is empty");  
              return 0;  
          }  
          else {  
                int leftMin, rightMin;  
                int min = temp.data;    
                if(temp.left != null){  
                  leftMin = smallestElement(temp.left);  
                  
                  min = Math.min(min, leftMin);  
                }  
  
                if(temp.right != null){  
                  rightMin = smallestElement(temp.right);  
                  min = Math.min(min, rightMin);  
                }  
                return min;  
          }  
      }  
  
      public static void main(String[] args) {  
  
        SN bt = new SN();  
         
        bt.root = new Node(4);  
        bt.root.left = new Node(2);  
        bt.root.right = new Node(3);  
        bt.root.left.left = new Node(1);  
        bt.root.right.left = new Node(5);  
        bt.root.right.right = new Node(6);  
  
          
        System.out.println(" Smallest element:" + bt.smallestElement(bt.root));  
      }  
}

Algorithm of the program:

  • We initialize a variables ‘MIN1″,’MIN2′,’MIN’ & stored the root node value in this variable ‘MIN1’.
  • We traverse the Left Subtree and Find the smallest element and stored in the ‘MIN2.
  • If ‘MIN2′>’MIN1’ then stored the value of ‘MIN1’ in the ‘MIN’ variable.
  • After that, we traverse the right subtree and find the smallest element.
  • If the smallest element of a right subtree is less than the value of the ‘MIN’ variable.
  • Swap the values between them.

In this program, we already give the values of the node.

The output of the program

The smallest element in the Tree: 3

Also, read,

Leave a Reply

Your email address will not be published. Required fields are marked *