Home » Program to Determine Whether all Leaves are at Same Level

Program to Determine Whether all Leaves are at Same Level

by Online Tutorials Library

Q. Program to determine whether all leaves are at same level.

Explanation

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.

Program to determine whether all leaves are at same level

Algorithm

  1. 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.
  2. When a node is created, data will pass to data attribute of the node and both left and right will be set to null.
  3. Define another class which has two attribute root and level.
    1. Root represents the root node of the tree and initializes it to null.
    2. The level will be used to store the level of the first encountered leaf node.
  4. isSameLevel() will check whether all leaves of given binary tree are at same level or not:
    1. It checks whether the root is null, which means the tree is empty.
    2. If the tree is not empty, traverse through the tree and check for leaf node whose left and right children are null.
    3. CurrentLevel will keep track of current level being traversed.
    4. When the first leaf node is encountered, store the value of currentLevel in variable level.
    5. 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.

Solution

Python

Output:

All leaves are at same level  

C

Output:

All leaves are at same level  

JAVA

Output:

All leaves are at same level  

C#

Output:

All leaves are at same level  

PHP

Output:

All leaves are at same level  

Next TopicPrograms List

You may also like