Find the type of Tree based on the child count
Last Updated :
28 Aug, 2023
Given a tree that has some nodes and each node has a certain number of child nodes, the task is to find the type of tree based on the child count. For example, if each node has two children, then we can say it is a binary tree, and if each node has almost three children, then we can say it is a Ternary tree.
Examples:
Input: A
/ | \
B C D
/ | \ / \
E F G H K
Output: Ternary Tree
Explanation: Here we can observe that each node has at most 3 children, which is basically the property of a ternary tree.
Input: A
/ \
B C
/ \ / \
E F H K
Output: Binary Tree
Explanation: Here we can observe that each node has 2 children, which is basically the property of a binary tree
Naive Approach: To solve the problem follow the below idea:
The basic way is to find the type of tree from the child count, we can iterate over each node and check the count of the child each node has and then we can easily determine the type of tree. It can be carried out in three steps first we traverse each node then we keep the count of children at each node and then at last we compare it with the conditions to get the type of the tree.
Time Complexity: O(N), where N is the number of nodes
Auxiliary Space: O(1)
Efficient Approach: In this approach, instead of keeping track of the child count of each node, we will take advantage of the properties of the specific tree that will help us to determine the type of tree without increasing the complexity of the program.
Dry run: Please consider the below example to understand the above approach easily
Tree: A
/ | \
B C D
/ | \ | \
E F G H K
In this example, the tree has 9 nodes
- Traverse each node in the tree.
- Check the child count of each node based on the predefined criteria for different types of trees.
- Identify the type of tree based on the child count of the nodes.
Here we can see that each node present in the tree has at most three children, from which we can say that this tree is a ternary tree in nature based on the count of the node.
Below is the implementation of the above approach in Python:
C++
#include <iostream>
#include <vector>
// Class representing a node in the tree
class Node {
public:
int data;
std::vector<Node*> children;
// Constructor to initialize the node with data
Node(int data) {
this->data = data;
}
};
// Function to determine the type of tree based on the
// maximum number of children
std::string functionTree(Node* root) {
int max_child_count = 0;
for (Node* child : root->children) {
int child_count = child->children.size();
if (child_count > max_child_count) {
max_child_count = child_count;
}
}
// Determine the type of tree based on the maximum
// number of children
if (max_child_count <= 2) {
return "Binary Tree";
}
else if (max_child_count <= 3) {
return "Ternary Tree";
}
else {
return "N-ary Tree";
}
}
int main() {
// Example tree construction
Node* root = new Node('A');
root->children.push_back(new Node('B'));
root->children.push_back(new Node('C'));
root->children.push_back(new Node('D'));
root->children[0]->children.push_back(new Node('E'));
root->children[0]->children.push_back(new Node('F'));
root->children[0]->children.push_back(new Node('G'));
root->children[2]->children.push_back(new Node('H'));
root->children[2]->children.push_back(new Node('K'));
// Call the function to determine the type of tree
std::string typeofTree = functionTree(root);
// Print the result
std::cout << "Optimized Approach: " << typeofTree << std::endl;
return 0;
}
Java
import java.util.ArrayList;
import java.util.List;
// Class representing a node in the tree
class Node {
int data;
List<Node> children;
// Constructor to initialize the node with data
Node(int data) {
this.data = data;
this.children = new ArrayList<>();
}
}
class GFG {
// Function to determine the type of tree based on the
// maximum number of children
public static String functionTree(Node root) {
int maxChildCount = 0;
for (Node child : root.children) {
int childCount = child.children.size();
if (childCount > maxChildCount) {
maxChildCount = childCount;
}
}
// Determine the type of tree based on the maximum
// number of children
if (maxChildCount <= 2) {
return "Binary Tree";
} else if (maxChildCount <= 3) {
return "Ternary Tree";
} else {
return "N-ary Tree";
}
}
public static void main(String[] args) {
// Example tree construction
Node root = new Node('A');
root.children.add(new Node('B'));
root.children.add(new Node('C'));
root.children.add(new Node('D'));
root.children.get(0).children.add(new Node('E'));
root.children.get(0).children.add(new Node('F'));
root.children.get(0).children.add(new Node('G'));
root.children.get(2).children.add(new Node('H'));
root.children.get(2).children.add(new Node('K'));
// Call the function to determine the type of tree
String typeOfTree = functionTree(root);
// Print the result
System.out.println("Optimized Approach: " + typeOfTree);
}
}
Python3
class Node:
def __init__(self, data):
self.data = data
self.children = []
def functionTree(root):
max_child_count = 0
for child in root.children:
child_count = len(child.children)
if child_count > max_child_count:
max_child_count = child_count
if max_child_count <= 2:
return "Binary Tree"
elif max_child_count <= 3:
return "Ternary Tree"
else:
return "N-ary Tree"
# Example
root = Node('A')
root.children.append(Node('B'))
root.children.append(Node('C'))
root.children.append(Node('D'))
root.children[0].children.extend([Node('E'), Node('F'), Node('G')])
root.children[2].children.append([Node('H'),Node('K')])
typeofTree = functionTree(root)
print("Optimized Approach:", typeofTree)
C#
using System;
using System.Collections.Generic;
// Class representing a node in the tree
class Node
{
public int Data;
public List<Node> Children;
// Constructor to initialize the node with data
public Node(int data)
{
Data = data;
Children = new List<Node>();
}
}
class GFG
{
// Function to determine the type of tree based on the
// maximum number of children
public static string FunctionTree(Node root)
{
int maxChildCount = 0;
foreach (Node child in root.Children)
{
int childCount = child.Children.Count;
if (childCount > maxChildCount)
{
maxChildCount = childCount;
}
}
// Determine the type of tree based on the maximum
// number of children
if (maxChildCount <= 2)
{
return "Binary Tree";
}
else if (maxChildCount <= 3)
{
return "Ternary Tree";
}
else
{
return "N-ary Tree";
}
}
public static void Main(string[] args)
{
// Example tree construction
Node root = new Node('A');
root.Children.Add(new Node('B'));
root.Children.Add(new Node('C'));
root.Children.Add(new Node('D'));
root.Children[0].Children.Add(new Node('E'));
root.Children[0].Children.Add(new Node('F'));
root.Children[0].Children.Add(new Node('G'));
root.Children[2].Children.Add(new Node('H'));
root.Children[2].Children.Add(new Node('K'));
// Call the function to determine the type of tree
string typeOfTree = FunctionTree(root);
// Print the result
Console.WriteLine("Optimized Approach: " + typeOfTree);
}
}
JavaScript
// Class representing a node in the tree
// Nikunj Sonigara
class Node {
constructor(data) {
this.data = data;
this.children = [];
}
}
// Function to determine the type of tree based on the
// maximum number of children
function functionTree(root) {
let maxChildCount = 0;
for (let child of root.children) {
let childCount = child.children.length;
if (childCount > maxChildCount) {
maxChildCount = childCount;
}
}
// Determine the type of tree based on the maximum
// number of children
if (maxChildCount <= 2) {
return "Binary Tree";
} else if (maxChildCount <= 3) {
return "Ternary Tree";
} else {
return "N-ary Tree";
}
}
// Example tree construction
let root = new Node('A');
root.children.push(new Node('B'));
root.children.push(new Node('C'));
root.children.push(new Node('D'));
root.children[0].children.push(new Node('E'));
root.children[0].children.push(new Node('F'));
root.children[0].children.push(new Node('G'));
root.children[2].children.push(new Node('H'));
root.children[2].children.push(new Node('K'));
// Call the function to determine the type of tree
let typeofTree = functionTree(root);
// Print the result
console.log("Optimized Approach: " + typeofTree);
OutputOptimized Approach: Ternary Tree
Time Complexity: O(N), where N is the number of nodes
Auxiliary Space: O(1)
Note: Although the Time and Space complexity of both brute and optimised approaches is the same, still the optimised approach avoids the redundant count of children at each node and comparison and helps in removing the overhead.
Similar Reads
Count the unique type of nodes present in Binary tree According to the property of a Binary tree, a node can have at most two children so there are three cases where a node can have two children, one child, or no child, the task is to track the count of unique nodes and return the total number of unique nodes that have no child, one child, and two chil
10 min read
Count the Number of Binary Search Trees present in a Binary Tree Given a binary tree, the task is to count the number of Binary Search Trees present in it. Examples: Input: 1 / \ 2 3 / \ / \ 4 5 6 7 Output: 4Here each leaf node represents a binary search tree and there are total 4 nodes. Input: 11 / \ 8 10 / / \ 5 9 8 / \ 4 6 Output: 6 Sub-tree rooted under node
10 min read
Print the nodes of Binary Tree having a grandchild Given a Binary Tree, the task is to print the nodes that have grandchildren. Examples: Input: Output: 20 8 Explanation: 20 and 8 are the grandparents of 4, 12 and 10, 14. Input: Output: 1 Explanation: 1 is the grandparent of 4, 5. Approach: The idea uses Recursion. Below are the steps: Traverse the
8 min read
Print the nodes of Binary Tree having a grandchild Given a Binary Tree, the task is to print the nodes that have grandchildren. Examples: Input: Output: 20 8 Explanation: 20 and 8 are the grandparents of 4, 12 and 10, 14. Input: Output: 1 Explanation: 1 is the grandparent of 4, 5. Approach: The idea uses Recursion. Below are the steps: Traverse the
8 min read
What are the different types of Nodes in a Tree Trees are nonlinear data structures that organize data hierarchically and in a recursive manner. It is a method of organizing and storing data in the computer in a way that makes it more effective to use. Nodes in the graph are connected via edges. It has different types of nodes which are called pa
4 min read
Find Count of Single Valued Subtrees Given a binary tree, write a program to count the number of Single Valued Subtrees. A Single Valued Subtree is one in which all the nodes have same value. Expected time complexity is O(n). Example: Input: root of below tree 5 / \ 1 5 / \ \ 5 5 5Output: 4There are 4 subtrees with single values.Input:
15+ min read