Java program to determine whether all leaves are at same level

In this program, we need to check whether all the leaves of the given binary tree are at same level or not.

A Node is said to be leaf if it doesn't have any child node. In the below diagram, nodes 4, 5 and 6 are leaf nodes as they don't have any child node. Nodes 4, 5 and 6 are present at the same level, i.e., Level 2.

Java program to determine whether all leaves are at same level

Algorithm

  • Define Node class which has three attributes namely: data left and right. Here, left represents the left child of the node and right represents the right child of the node.
  • When a node is created, data will pass to data attribute of the node and both left and right will be set to null.
  • Define another class which has two attribute root and level.
    • Root represents the root node of the tree and initializes it to null.
    • The level will be used to store the level of the first encountered leaf node.

a. isSameLevel() will check whether all leaves of given binary tree are at same level or not:

  • It checks whether the root is null, which means the tree is empty.
  • If the tree is not empty, traverse through the tree and check for leaf node whose left and right children are null.
  • CurrentLevel will keep track of current level being traversed.
  • When the first leaf node is encountered, store the value of currentLevel in variable level.
  • Traverse recursively through all level, check for subsequent leaf nodes. If currentLevel of all leaf is equal to the value stored in level then, all leaves are at same level.

Program:

Output:

All leaves are at same level
Next TopicJava Programs




Latest Courses