Check if all Leaf Nodes are at same level in Binary tree

Question:

Given a binary tree root node, check if all Leaf Nodes are at same level in Binary tree

Solution:

We can solve this question with the help of pre-order traversal.

First we visit the left leaf and update the level value, and then check with the right leaf.
If both are same we return true, else we return false.

Solution in C++

#include <iostream>
#include <queue>
#include <stack>
using namespace std;

// structure to hold binary tree node
struct Node
{
    int data;
    Node *left, *right;

    Node(int data)
    {
        this->data = data;
        this->left = this->right = nullptr;
    }
};

int level_of_leaf = 0;

bool are_all_leaf_same_level(Node *node, int level) 
{
    if (node == NULL) 
    {
      return true;
    }

    if (node->left == NULL && node->right == NULL) 
    {
      if (level_of_leaf == 0) 
      {
        level_of_leaf = level;
        return true;
      }

      return level_of_leaf == level;
    }

    return are_all_leaf_same_level(node->left, level + 1) && are_all_leaf_same_level(node->right, level + 1);
}

int main()  
{  
    Node* root = nullptr;
    /* Binary tree:
              16
            /   \
           /     \
          10      25
         /  \    /  \
        /    \  /    \
       7    15 18     30

    */

    root = new Node(16);
    root->left = new Node(10);
    root->right = new Node(25);
    root->left->left = new Node(7);
    root->left->right = new Node(15);
    root->right->left = new Node(18);
    root->right->right = new Node(30);

    if (are_all_leaf_same_level(root, 0))
    {
        cout<<"All leaf are at same level"<<endl;
    } else {
        cout<<"All leaf are NOT at same level"<<endl;
  
    }

    return 0;  
} 

Output:

All leaf are at same level

 

 

 

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *