×

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

How to Convert int to char in Java

To convert a higher data type to lower data type, we need to do typecasting. Casting is also required when we want to convert ASCII value into character. It is...

3 minutes read.

New Features of Java 14

 Features like Switch expressions and text blocks which are previewed in Java 13 version are standardized in Java 14. Features in Java 14 Switch ExpressionText BlocksRecordsNull Pointer ExceptionsInstance ofPackaging ToolGarbage collectors 1.Switch Expressions Switch...

3 minutes read.

File Operation in Java

In Java, a file is an Abstract data type. These are used to store the data which is related. Files are named storage locations. With a file we can perform...

7 minutes read.

User Defined Custom Exceptions in Java

In this tutorial, we will discuss user-defined custom exceptions with examples. Introduction In Java, we have proactively characterised, Exception classes, for example, ArithmeticException, NullPointerException, ArrayoutOfBound and so on. These built-in exceptions are...

3 minutes read.

Java Math ulp() Method

The ulp() method of Java Math class returns the size of an ulp of the argument. Syntax: public static double ulp(double x)public static float ulp(float x) Parameters: The parameter ‘x’ represents the floating-point number...

2 minutes read.

Convert JSON to Map in Java

JACKSON and GSON libraries are two extremely capable JSON-related libraries offered by Java. To efficiently work with the returned JSON data, we frequently need to convert JSON responses into a...

6 minutes read.

Java Integer reverseByte() method

The reverseByte() method of Java Integer class returns the value obtained by reversing the order of the bytes in the 2’s complement binary representation. Syntax public static int reverseByte (int i) Parameters The parameter...

1 minute read.

Constructor Program in Java

Constructor Program in Java In Java, a constructor is a piece of code that is used to create an object. A constructor is called implicitly when an object is created in...

7 minutes read.

Snake and Ladder Problem in Java

Find the smallest number of dice throws necessary to reach the destination or last cell from the source or first cell on a snake and ladder board. Essentially, the player...

6 minutes read.

Java Error Stack Trace

The stack trace in Java is an array of stacks.The stack trace reveals the console's location of an exception or error by gathering data from all program methods. The JVM...

3 minutes read.

Java 9 Interface Private Method

Java 9 provides us the facility to include private methods inside the java interface. In java 8 and earlier versions, we are supposed to use only constant variables and abstract...

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

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.

Tilt operator in Java | Tilde operator in Java Example

The symbol designates it as a unary operator (pronounced as the tilde). It gives back the bit's complement or inverse. Every 0 turns into a 1, and every 1 back...

3 minutes read.

Java Math sin() Method

The sin() method of Java Math class returns the trigonometric sine of the specified angle. Syntax: public static double sin(double a) Parameters: The parameter ‘a’ represents an angle measured in radians. Return Value: The sin() method...

1 minute read.

Split String into String Array in Java

The String split() technique returns a variety of divided strings after the strategy parts the given String around matches of a given normal articulation containing the delimiters. The ordinary articulation...

4 minutes read.

Java Boolean Keyword

Boolean keyword In java programming language we basically have two types of primitive data types, Boolean and Numeric (integer and floating-point data types). In this article we are going to learn...

4 minutes read.

Java Math nextDown() Method

The nextDown() method of Math class returns the floating-point number adjacent to the argument in direction of the negative infinity. Syntax: public static double nextDown (double d)public static float nextDown (float f) Parameters: The...

2 minutes read.

Read JSON file in Java

 To know about reading a JSON file in Java first we must know about the JSON file. JSON: JSON is “JavaScript Object Notation”. The JSON is the simple format for storing and...

3 minutes read.

Compare time in java

Introduction: This article discusses how to compare time in java. Maximum of the time we need to examine the date and datetime items. Date comparisons are vital if you want to...

3 minutes read.