×

Java program to determine whether all leaves are at same level

In this program, we must determine whether or not all of the binary tree's leaves are at the same level.

If a node has no child nodes, it is said to be a leaf. Nodes 10, 14, and 12 in the figure below are leaf nodes since they don't have any child nodes. Level 2 has Nodes 10, 14, and 12.

Java program to determine whether all leaves are at same level

Algorithm

  • Define the Node class, which has three properties: data left, data right, and cloud server. Left here 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 formation, and left and right are both set to null.
  • Define a different class with the parameters root and level.
  • Root initialises the root node of the tree to null and represents it.
  • The first leaf node encountered will have its level saved in the level.

The function isSameLevel() determines whether or not every node in a binary tree is at the same level.

  • It verifies to see if the root is null, which implies an empty tree.
  • Navigate the tree and search about any tree structure with null left and right children if it is not empty.
  • The level that is currently being travelled will be maintained by CurrentLevel.
  • Save the currentLevel value in the variable level when the first leaf node is reached.
  • Recursively traverse each level, looking for more tree structure. All leaves are at the same level if currentLevel for every leaf equals the value contained in level.

LeafLevel.java

public class LeafLevel {  
    //represent a binary tree node.
    public static class Node{  
        int data;  
        Node left;  
        Node right; 
        public Node(int data){  
            //Give the new node data, and then set the left and right children to null  
            this.data = data;  
            this.left = null;  
            this.right = null;  
            }  
        }  
    //represent the binary tree's root 
    public Node root;  
    //It will save the first encountered leaf level.  
    public static int level = 0;    
    public LeafLevel(){  
        root = null;  
    }    
    //If the binary tree's leaves are all at the same level, isSameLevel() will determine whether they are  
    public boolean isSameLevel(Node temp, int currentLevel ) {   
        //Verify that the tree is empty.
        if(root == null){  
          System.out.println("Tree is empty");  
          return true;  
        }  
        else {  
            //determines whether node is null 
            if(temp==null)  
                return true;    
            if(temp.left == null && temp.right == null) {  
                //If the first leaf is found, the level is set to the current level.  
                if(level == 0) {  
                    level = currentLevel ;  
                    return true;  
                }  
                //analyzes the other leaves to see if they are at the same level as the first leaf 
                else  
                   return (level == currentLevel) ;  
             }  
 
            //iteratively looks for leaf nodes in the left and right subtrees. 
            return  (isSameLevel(temp.left, currentLevel + 1) && isSameLevel(temp.right, currentLevel + 1)) ;  
         }  
    }    
    public static void main (String[] args) {   
        LeafLevel bt = new LeafLevel();  
        //Adding nodes to the binary tree 
        bt.root = new Node(2);  
        bt.root.left = new Node(4);  
        bt.root.right = new Node(6);  
        bt.root.left.left = new Node(8);  
        bt.root.right.left = new Node(10);  
        bt.root.right.right = new Node(12);    
        //determines if every leaf in a binary tree is at the same level.
        if(bt.isSameLevel(bt.root, 1))  
            System.out.println("The level of each leaf is the same.");  
        else  
            System.out.println("The level of each leaf is the not same");  
  }  
}  

Output:

Java program to determine whether all leaves are at same level

Related Topics

Java StringWriter Class

The StringWriter class is a character stream in which it is used to store the output consisting of characters into the string buffer. Upon collecting output into a string buffer,...

3 minutes read.

Java String isEmpty() method

Java String isEmpty() method checks whether current String is empty or not. Syntax: public boolean isEmpty() Returns It returns true, if length of String is 0 otherwise false. Java String isEmpty() method example 1    ...

1 minute read.

Java Flags Enum

In a programming language, enumerations represent a group of named constants.For instance; the four suits in a deck of playing cards could be the enumerators Club, Diamond, Heart, and Spade,...

3 minutes read.

Methods in Java

The Methods in Java are the collection of statements that are executed when the method is called. By using the methods, the complexity of writing the code decreases. The method consists...

4 minutes read.

Java SHA256

Definition: In cryptography, SHA is a hash function that takes 20 bytes of input and produces an approximate 40-digit hexadecimal integer as the hash result. Class for Message Digest: Java's MessageDigest Class,...

2 minutes read.

How to get Day Name from Date in Java

We'll write a Java application to extract the day's name from the Date in this section. When dealing with Date and time in Java, the following classes are used. Class for Calendars:...

6 minutes read.

How to Create an Object in Java

How to Create an Object in Java An object can be defined as a run time entity that contains the blue printof the class. It means that all the member functions...

5 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.

InputMismatchException in Java

What is InputMismatchException? One of the most frequent errors in Java is the InputMismatchException. Because the InputMismatchException is a subtype of the java.lang, it is an unchecked exception. RuntimeException.Because it is...

4 minutes read.

Hierarchy of operators in Java

Operators are the most frequently used terminology in any area of programming, and it helps in various approaches to efficiently solve daily life problems by computer programming. The simple addition of...

4 minutes read.

Blocking Queue in Java Example

Let's first briefly comprehend queue before moving on to the topic of "Blocking Queue." A queue seems to be an orderly list of items in which elements are added from...

8 minutes read.

Convert Integer to Roman Numerals in Java

The main objective of this article is to convert the integers that are decimal values to the roman numbers. Problem statement: Write a software/program/code to convert any integer to a roman number. You...

10 minutes read.

Java Math incrementExact() Method

The incrementExact() method of Math class returns the argument incremented by one, throwing an exception if the result overflows an int or a long. Syntax: public static int incrementExact (int a)public static...

1 minute read.

Java Arrays Fill

We may use the Arrays.fill () function to fill a whole array or a subset of it. Arrays.fill () may fill both 2D and 3D arrays. Syntax: Arrays.fill(boolean[] fillArr, int fromIndex, int toIndex, boolean val )   Parameters: The array to be filled...

4 minutes read.

Java Return Keyword

The return keyword in Java is used to end a method's execution. the caller receives the return, followed by the appropriate value. The return type of the method, such as...

3 minutes read.

Java Base64 Encoding and Decoding

Introduction to Encoding and Decoding Encoding is the process of putting the sequence of characters like letters, numbers, punctuations, and other symbols into a specialised format for the efficient transmission or...

11 minutes read.

Java Class Methods

Methods called on a class rather than a specific object instance are known as class methods. The static modifier guarantees uniform implementation across all instances of the class. Syntax public class NameOfClass...

3 minutes read.

Java FileOutputStream

What is FileOutputStream?When we need raw stream data written into a file, we need to look for another option: FileOutputStream. It is used when the file's data is byte-oriented. It comes under...

4 minutes read.

Java Byte intValue() method

The intValue()  method of Java Integer class returns an int value for this Integer.  Syntax public int intValue()  Parameters NA  Specified by This method is specified by intValue in class Number  Return Value This method returns the numeric...

1 minute read.

Java Integer toBinaryString() method

The toBinaryString() method of Java Integer class returns a string representing the specified int argument as an unsigned integer in base 2. Syntax public static String toBinaryString (int  i)  Parameters The parameter ‘i’ represents...

1 minute read.