×

Java Program to find the smallest element in a tree

The variable min is used to store the data of the root, which is initially defined. The smallest node in the left subtree is then located by moving through the subtree. It is compared to a min, and a minimum of two is stored in the variable min. Next, we search the current subtree for the smallest node, compare it to min, and move on. Variable Min will have the smallest node at the end of the traversal.

Algorithm

  • Define Data; left and right is the node class's three characteristics. Left indicates the node's left child, and right here represents the node's right child.
  • Data is passed to the node's data attribute at creation, and left, and right are both set to null.
  • Define a different class with a root attribute.
  • Root initializes to null and represents the tree's root node.
  • The function smallestElement() will determine the binary tree's smallest node:
    1. If the root of the given tree is null, then it is assumed to be empty.
    2. Create a variable called min that will hold the data from temp if the tree is not empty.
    3. Recursively executing smallestElement() will reveal the smallest node in the left subtree. Put that number in leftMin. The minimum of two is stored in a min after comparing the min value with leftMin.
    4. Recursively invoking smallestElement() will reveal the smallest node in the right subtree. Put that number into rightMin. The maximum of two should be stored in a min after comparing the value of min with rightMin.
    5. The smallest binary tree node will be stored in min at the conclusion.

SmallestNodeInTree.java

// Main class declaration for finding the smallest number in the tree 
public class SmallestNodeInTree {   
    // creating the Node for the tree using static keyword
    // By Using static keyword, we can access the method without creating the object 
      public static class Node {  
        // storing the data
        int data;  
        /* Left Node creation to store left node of the tree */
        Node left;  
        /* Right Node creation to store the right node of the tree */
        Node right;  
        /* Node parameterized constructor creation */ 
        public Node(int data){  
            /* Set the left and right children to null and assign data to the new node */
            /* this keyword is used to represent the present class */
            this.data = data;  
            this.left = null;  
            this.right = null;  
        }  
      }  
  
      /* Node root represents the root of the binary tree */ 
      public Node r;  
  
      public Node SmallestNode(){  
          r = null; 
          return r;
      }  
  
      /* smallestElement() will identify the binary tree's smallest node. */  
      public int smallestElement(Node cur){  
          /* Verify if the tree is empty. */ 
          if(r == null) {  
              System.out.println(" The  Tree is empty" );  
              return 0 ;  
          }  
          else {  
              // creating two integer variables 
                int lMin, rMin; 
                // storing the node data into min variable
                int min = cur.data;  
  
                // this if block is used to find the smallest Element in the left sub tree of the given node //
               
                if(cur.left != null){  
                  lMin = smallestElement(cur.left);  
                  // Store the value of leftMin into min if min is greater than leftMin value. 
                  min = Math.min(min, lMin);  
                }  
                 // this if block is used to find the smallest Element in the left sub tree of the given node 
                 
                if(cur.right != null){  
                  rMin = smallestElement(cur.right);  
                  // If min value   is greater than rightMin value, then store the value of rightMin into min  
                  min = Math. min(min, rMin);  
                }  
                return min;  
          }  
      }  
      public static void main (String[] args) {  
        SmallestNodeInTree t = new SmallestNodeInTree();  
        //  Adding  nodes to the binary tree by calling the parameterized constructor
        // adding a root node
        t.r = new Node(4);  
        // adding a left node to the tree
        t.r.left = new Node(2); 
        // adding a right node to the tree
        t.r.right = new Node(3);  
        // adding a left node to the left sub tree
        t.r.left.left = new Node(9);  
        // adding a right node to the right sub tree
        t.r.right.right = new Node(5);  
        //  adding a left node to the right sub tree
        t.r.right.left = new Node(6);
        // Print the  smallest node in the given binary tree 
        System.out.println("The Smallest element in the binary tree: " + t.smallestElement(t.r));  
      }  
}  

Output

The smallest element in the binary tree: 2

Related Topics

Console Errors in Java

An unlawful motion taken through the person that reasons this system to act abnormally is amistake until this system is compiled or run; maximum programming mistakes pass unnoticed.The software is...

3 minutes read.

Java Math rint() Method

The rint() method of Java Math class returns the double value which is close to the specified argument and is equal to mathematical integer. Syntax: public static double rint(double a) Parameters: The parameter ‘a’...

1 minute read.

Java Char Keyword

The java char keyword is a data type which is defined as character data type.Char keyword belongs to a primitive data type where the data types are classified into primitive...

4 minutes read.

Java Viva Questions and Answers

Question: Explain Java programming language. Answer: It is a high-level programming language. This programming language is based on the principles of object-oriented programming. Large-scale applications can be developed by using this...

16 minutes read.

Transient variable in Java

In this article, you will be acknowledged about transient variable along with its functions. We would conclude by understanding an example program about it. Transient variable By introducing the transitory keyword, we...

3 minutes read.

Morris Traversal for Inorder in Java

Through Morris’s traversal, a tree is traversed without the aid of recursion or stacks. Based on the threaded binary tree, the Morris traversal is used. We perform internal modification throughout...

4 minutes read.

Java Math IEEEremainder() Method

The IEEEremainder() method of Math class calculates the remainder as prescribed by the IEEE754 standard. This method simply returns the remainder when f1 (dividend) is divided by f2 (divisor). Syntax: public static...

2 minutes read.

How annotations work in Java

Annotations were introduced by sun microsystem and are available from the java 1.5 version. In general, configurations can be done either by XML or by annotations. Hibernate and spring framework users prefer...

4 minutes read.

Java Destructors

Before knowing about Java destructors, let us know about constructors. If we understand the concept of the constructor, we can easily understand about destructor and also, we will get an...

3 minutes read.

Iccanobif Numbers in Java

In this article, you will be very well equipped with the knowledge of iccanobif numbers in Java. You will also know how they are formed and basic example programs on...

3 minutes read.

Anagram Program in Java using String

Anagram Program in Java Anagrams are those words that are generated by rearrangement of the letters of another phrase or word. Usually, while doing the rearrangement, the original letters are used...

8 minutes read.

How to Create Singleton Class in Java

In this tutorial, we will discuss the singleton class and how to create it. Introduction Java is a purely object-oriented programming language. It consists of classes and objects. But Singleton is one...

4 minutes read.

Java String Methods

Java String Methods Java String class is the most important class of the java.lang package. It is used to handle the String related operations. It contains a lot of built-in Java...

2 minutes read.

Object Definition in Java

In this article, you will be acknowledged about object in Java, its definition and how is this useful in writing the programs in Java. The comprehension of object-oriented technology depends on...

4 minutes read.

Difference Between replace() and replaceall() in Java

In this article, you will be acknowledged about the replace() and replaceall() methods in java. Also, most importantly you will be acknowledged the differences between them along with the example...

4 minutes read.

Java Math sinh() Method

The sinh() method of Java Math class returns the hyperbolic sine of the specified double value. Syntax: public static double sinh(double x) Parameters: The parameter ‘a’ represents the number whose hyperbolic sine is to...

2 minutes read.

Java Double Keyword

In java primitive data types, we have two different types of data types which are Boolean and floating-point data types.In floating data type again we have four types which are...

3 minutes read.

If Condition in Lambda Expression Java

The new and significant lambda expression feature of Java was added in Java SE 8. It provides a clear and concise mechanism for describing a single-method interface using an expression....

4 minutes read.

Get year from date in Java

The getYear() method of the Java date class returns a number calculated by deducting 1900 from the year that contains or starts with the instant in time represented by this...

4 minutes read.

How to Convert String to Object in Java

How to Convert String to Object in Java The Object is the super class of all classes. So you can assign a string to Object directly. There are two methods to...

3 minutes read.