×

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

Java Snippets

The term "snippet" refers to a section of code that addresses numerous issues with just a few lines of code. Decreases the number of lines of code and improves programmer...

3 minutes read.

Three Partition Problems in Java

In talks with leading IT organizations like Google, Amazon, TCS, Accenture, etc., this extremely intriguing subject is constantly brought up. The goal of the problem-solving exercise is to evaluate the...

8 minutes read.

How to Create Different Packages for Different Classes in Java

Packages in Java In Java, Packages are an assortment of classes, sub-packages, and connection points. i.e. A package addresses a word reference that contains a connected gathering of styles and points...

7 minutes read.

The Maximum Rectangular Area in a Histogram in Java

Continuous bars should be used to form the largest possible rectangle. We'll assume in the interest of convenience that each bar's width is 1. Naive Approach In this method, each bar will be...

6 minutes read.

XNOR operator in Java

The opposite of the binary equivalent of XOR is given by XNOR. Truth table: XYXNOR001010100111 If the bits are the same, it returns 1, else it returns 0. Examples:  Input: 10 20 Output : 1 A Binary...

3 minutes read.

Java String substring() method

Java String substring() method returns a part of the String. Syntax: public String substring(int startIndex) public String substring(int startIndex, int endIndex) Parameters: startIndex : starting index endIndex : ending index Returns: It returns a specified String. Throws: StringIndexOutOfBoundsException if start...

2 minutes read.

Java Keywords

Java Keywords The particular words which are used in java programming language that act like a key or important words to write a code are called java keywords. Java Keywords are...

4 minutes read.

Java List Interface

List interface is used when we have to order a collection which contains duplicate entries. Like an array, the elements of its implementation classes are retrieved and inserted at a...

2 minutes read.

Basic Terms in Multithreading

To understand the terms of multithreading, we must have knowledge about concurrency, processes, and threads. Concurrency The concurrency stands for performing multiple tasks at the same time. In the process communication, the operating system permits the process...

8 minutes read.

MVC in Java

A well-known design pattern is Model-View-Controller. The discipline of web development. We can organize our code in this manner. The document stipulates that a program or application must include a...

4 minutes read.

Java Math log1p() Method

The log1p() method of Math class returns the natural logarithmic sum for the specified double argument and 1. Its value is much closer to result of ln(1 + x). Syntax: public static...

2 minutes read.

How to convert String to String array in Java

A String in Java is a thing that indicates a collection of letters. We must include the String class from java.lang package if we want to be using strings. An...

5 minutes read.

Java Font

The font is a Java class that is a part of java.awt package. The Serializable interface is implemented by it. The direct recognized child of a Java Font class is...

8 minutes read.

Association in Java

In Java, association refers to the link between two classes established by their objects. One-to-one, one-to-many, and many-to-many connections are managed via association. The Association defines the multiplicity between objects...

5 minutes read.

PriorityQueue in Java

PriorityQueue in Java A PriorityQueue is a member of the Java Collection Framework and is used when the values are needed to be processed based on priority. Priority queue operates similar to...

8 minutes read.

Program to check whether a given character is present in a string or not

In this article, you will understand the logic to find out whether the given character is present in the string or not and find out the position of the specified...

3 minutes read.

Upcasting and Downcasting in Java

Type casting in Java is an important and very interesting topic to deal with. But here upcasting and downcasting is somewhat related to typecasting. In normal typecasting, we convert from...

6 minutes read.

Mutable and Immutable in Java

Java is a programming language in which everything is treated as an object. Its procedures and functions are centred around objects because it is an object-oriented programming language. Mutable and...

6 minutes read.

Java this keyword

This Keyword in Java This keyword can be used in many different ways in Java. This is a reference variable in Java that points to the active object. In Java, the...

8 minutes read.

Prime Number Program in Java Using a Scanner

In Java, a prime number is one that can only be divided by one or by itself and is greater than one. In other words, only one or itself can...

3 minutes read.