Check if the given n-ary tree is a binary tree

Given an n-ary tree, the task is to check whether the given tree is binary or not.

Examples:

Input: 
    A 
   / \  
  B   C
 / \   \
D   E   F
Output: Yes

Input: 
     A 
   / | \  
  B  C  D
         \
          F
Output: No

Approach: Every node in a binary tree can have at most 2 children. So, for every node of the given tree, count the number of children and if for any node the count exceeds 2 then print No else print Yes.

Below is the implementation of the above approach:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
  
// Structure of a node
// of an n-ary tree
struct Node {
    char key;
    vector<Node*> child;
};
  
// Utility function to create
// a new tree node
Node* newNode(int key)
{
    Node* temp = new Node;
    temp->key = key;
    return temp;
}
  
// Function that returns true
// if the given tree is binary
bool isBinaryTree(struct Node* root)
{
  
    // Base case
    if (!root)
        return true;
  
    // Count will store the number of
    // children of the current node
    int count = 0;
    for (int i = 0; i < root->child.size(); i++) {
  
        // If any child of the current node doesn't
        // satify the condition of being
        // a binary tree node
        if (!isBinaryTree(root->child[i]))
            return false;
  
        // Increment the count of children
        count++;
  
        // If current node has more
        // than 2 children
        if (count > 2)
            return false;
    }
    return true;
}
  
// Driver code
int main()
{
    Node* root = newNode('A');
    (root->child).push_back(newNode('B'));
    (root->child).push_back(newNode('C'));
    (root->child[0]->child).push_back(newNode('D'));
    (root->child[0]->child).push_back(newNode('E'));
    (root->child[1]->child).push_back(newNode('F'));
  
    if (isBinaryTree(root))
        cout << "Yes";
    else
        cout << "No";
  
    return 0;
}

chevron_right


Output:

Yes


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


2


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.