Open In App

Print levels with odd number of nodes and even number of nodes

Last Updated : 12 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given an N-ary tree, print all the levels with odd and even numbers of nodes in it. 

Examples

For example consider the following tree
1 - Level 1
/ \
2 3 - Level 2
/ \ \
4 5 6 - Level 3
/ \ /
7 8 9 - Level 4

The levels with odd number of nodes are: 1 3 4
The levels with even number of nodes are: 2

Note: The level numbers starts from 1. That is, the root node is at the level 1.

Approach

  • Insert all the connecting nodes to a 2-D vector tree.
  • Run a DFS on the tree such that height[node] = 1 + height[parent]
  • Once DFS traversal is completed, increase the count[] array by 1, for every node’s level.
  • Iterate from first level to last level, and print all nodes with count[] values as odd to get level with odd number nodes.
  • Iterate from first level to last level, and print all nodes with count[] values as even to get level with even number nodes.

Below is the implementation of the above approach:

C++
// C++ program to print all levels
// with odd and even number of nodes

#include <bits/stdc++.h>
using namespace std;

// Function for DFS in a tree
void dfs(int node, int parent, int height[], int vis[],
         vector<int> tree[])
{
    // calculate the level of every node
    height[node] = 1 + height[parent];

    // mark every node as visited
    vis[node] = 1;

    // iterate in the subtree
    for (auto it : tree[node]) {

        // if the node is not visited
        if (!vis[it]) {

            // call the dfs function
            dfs(it, node, height, vis, tree);
        }
    }
}

// Function to insert edges
void insertEdges(int x, int y, vector<int> tree[])
{
    tree[x].push_back(y);
    tree[y].push_back(x);
}

// Function to print all levels
void printLevelsOddEven(int N, int vis[], int height[])
{
    int mark[N + 1];
    memset(mark, 0, sizeof mark);

    int maxLevel = 0;
    for (int i = 1; i <= N; i++) {

        // count number of nodes
        // in every level
        if (vis[i])
            mark[height[i]]++;

        // find the maximum height of tree
        maxLevel = max(height[i], maxLevel);
    }

    // print odd number of nodes
    cout << "The levels with odd number of nodes are: ";
    for (int i = 1; i <= maxLevel; i++) {
        if (mark[i] % 2)
            cout << i << " ";
    }

    // print even number of nodes
    cout << "\nThe levels with even number of nodes are: ";
    for (int i = 1; i <= maxLevel; i++) {
        if (mark[i] % 2 == 0)
            cout << i << " ";
    }
}

// Driver Code
int main()
{
    // Construct the tree

    /*   1
       /   \
      2     3
     / \     \
    4    5    6
        / \  /
       7   8 9  */

    const int N = 9;

    vector<int> tree[N + 1];

    insertEdges(1, 2, tree);
    insertEdges(1, 3, tree);
    insertEdges(2, 4, tree);
    insertEdges(2, 5, tree);
    insertEdges(5, 7, tree);
    insertEdges(5, 8, tree);
    insertEdges(3, 6, tree);
    insertEdges(6, 9, tree);

    int height[N + 1];
    int vis[N + 1] = { 0 };

    height[0] = 0;

    // call the dfs function
    dfs(1, 0, height, vis, tree);

    // Function to print
    printLevelsOddEven(N, vis, height);

    return 0;
}
Java
// Java program to print all levels
// with odd and even number of nodes
import java.util.*;

@SuppressWarnings("unchecked") 
class GFG{
 
// Function for DFS in a tree
static void dfs(int node, int parent, 
                int []height, int []vis,
                ArrayList []tree)
{
    
    // Calculate the level of every node
    height[node] = 1 + height[parent];
  
    // Mark every node as visited
    vis[node] = 1;
  
    // Iterate in the subtree
    for(int it : (ArrayList<Integer>)tree[node]) 
    {
        
        // If the node is not visited
        if (vis[it] == 0)
        {
            
            // Call the dfs function
            dfs(it, node, height, vis, tree);
        }
    }
}
  
// Function to insert edges
static void insertEdges(int x, int y, 
                        ArrayList []tree)
{
    tree[x].add(y);
    tree[y].add(x);
}
  
// Function to print all levels
static void printLevelsOddEven(int N, int []vis, 
                               int []height)
{
    int []mark = new int[N + 1];
    Arrays.fill(mark, 0);
    int maxLevel = 0;
    
    for(int i = 1; i <= N; i++)
    {
        
        // Count number of nodes
        // in every level
        if (vis[i] != 0)
            mark[height[i]]++;
  
        // Find the maximum height of tree
        maxLevel = Math.max(height[i], maxLevel);
    }
  
    // Print odd number of nodes
    System.out.print("The levels with odd " + 
                     "number of nodes are: ");
     
    for(int i = 1; i <= maxLevel; i++) 
    {
        if (mark[i] % 2 != 0)
        {
            System.out.print(i + " ");
        }
    }
  
    // Print even number of nodes
    System.out.print("\nThe levels with even " + 
                     "number of nodes are: ");
     
    for(int i = 1; i <= maxLevel; i++)
    {
        if (mark[i] % 2 == 0)
        {
            System.out.print(i + " ");
        }
    }
}
     
// Driver code  
public static void main(String []s)
{
    
    // Construct the tree
     
    /*   1
       /   \
      2     3
     / \     \
    4    5    6
        / \  /
       7   8 9  */
     
    int N = 9;
     
    ArrayList []tree = new ArrayList[N + 1];
     
    for(int i = 0; i < N + 1; i++)
    {
        tree[i] = new ArrayList();
    }
     
    insertEdges(1, 2, tree);
    insertEdges(1, 3, tree);
    insertEdges(2, 4, tree);
    insertEdges(2, 5, tree);
    insertEdges(5, 7, tree);
    insertEdges(5, 8, tree);
    insertEdges(3, 6, tree);
    insertEdges(6, 9, tree);
     
    int []height = new int[N + 1];
    int []vis = new int[N + 1];
    Arrays.fill(vis, 0);
     
    height[0] = 0;
     
    // Call the dfs function
    dfs(1, 0, height, vis, tree);
     
    // Function to print
    printLevelsOddEven(N, vis, height);
}
}

// This code is contributed by pratham76
Python3
# Python3 program to print all levels 
# with odd and even number of nodes 

# Function for DFS in a tree 
def dfs(node, parent, height, vis, tree): 

    # calculate the level of every node 
    height[node] = 1 + height[parent] 

    # mark every node as visited 
    vis[node] = 1

    # iterate in the subtree 
    for it in tree[node]: 

        # if the node is not visited 
        if not vis[it]: 

            # call the dfs function 
            dfs(it, node, height, vis, tree) 
        
# Function to insert edges 
def insertEdges(x, y, tree): 

    tree[x].append(y) 
    tree[y].append(x) 

# Function to print all levels 
def printLevelsOddEven(N, vis, height): 

    mark = [0] * (N + 1) 
    
    maxLevel = 0
    for i in range(1, N + 1): 

        # count number of nodes in every level 
        if vis[i]: 
            mark[height[i]] += 1

        # find the maximum height of tree 
        maxLevel = max(height[i], maxLevel) 
    
    # print odd number of nodes 
    print("The levels with odd number",
          "of nodes are: ", end = "") 
    for i in range(1, maxLevel + 1): 
        if mark[i] % 2: 
            print(i, end = " ") 
    
    # print even number of nodes 
    print("\nThe levels with even number", 
          "of nodes are: ", end = "") 
    for i in range(1, maxLevel + 1): 
        if mark[i] % 2 == 0: 
            print(i, end = " ") 

# Driver Code 
if __name__ == "__main__":

    # Construct the tree
    N = 9
    tree = [[] for i in range(N + 1)] 

    insertEdges(1, 2, tree) 
    insertEdges(1, 3, tree) 
    insertEdges(2, 4, tree) 
    insertEdges(2, 5, tree) 
    insertEdges(5, 7, tree) 
    insertEdges(5, 8, tree) 
    insertEdges(3, 6, tree) 
    insertEdges(6, 9, tree) 

    height = [0] * (N + 1)
    vis = [0] * (N + 1) 

    # call the dfs function 
    dfs(1, 0, height, vis, tree) 

    # Function to print 
    printLevelsOddEven(N, vis, height) 

# This code is contributed by Rituraj Jain
C#
// C# program to print all levels
// with odd and even number of nodes
using System;
using System.Collections;

class GFG{

// Function for DFS in a tree
static void dfs(int node, int parent, 
                int []height, int []vis,
                ArrayList []tree)
{
    
    // Calculate the level of every node
    height[node] = 1 + height[parent];
 
    // Mark every node as visited
    vis[node] = 1;
 
    // Iterate in the subtree
    foreach (int it in tree[node]) 
    {
        
        // If the node is not visited
        if (vis[it] == 0)
        {
            
            // Call the dfs function
            dfs(it, node, height, vis, tree);
        }
    }
}
 
// Function to insert edges
static void insertEdges(int x, int y, 
                        ArrayList []tree)
{
    tree[x].Add(y);
    tree[y].Add(x);
}
 
// Function to print all levels
static void printLevelsOddEven(int N, int []vis, 
                               int []height)
{
    int []mark = new int[N + 1];
    Array.Fill(mark, 0);
 
    int maxLevel = 0;
    for(int i = 1; i <= N; i++)
    {
        
        // Count number of nodes
        // in every level
        if (vis[i] != 0)
            mark[height[i]]++;
 
        // Find the maximum height of tree
        maxLevel = Math.Max(height[i], maxLevel);
    }
 
    // Print odd number of nodes
    Console.Write("The levels with odd " + 
                  "number of nodes are: ");
    
    for(int i = 1; i <= maxLevel; i++) 
    {
        if (mark[i] % 2 != 0)
        {
            Console.Write(i + " ");
        }
    }
 
    // Print even number of nodes
    Console.Write("\nThe levels with even " + 
                  "number of nodes are: ");
    
    for(int i = 1; i <= maxLevel; i++)
    {
        if (mark[i] % 2 == 0)
        {
            Console.Write(i + " ");
        }
    }
}
    
// Driver code  
static void Main()
{
      
    // Construct the tree
    
    /*   1
       /   \
      2     3
     / \     \
    4    5    6
        / \  /
       7   8 9  */
    
    int N = 9;
    
    ArrayList []tree = new ArrayList[N + 1];
    
    for(int i = 0; i < N + 1; i++)
    {
        tree[i] = new ArrayList();
    }
    
    insertEdges(1, 2, tree);
    insertEdges(1, 3, tree);
    insertEdges(2, 4, tree);
    insertEdges(2, 5, tree);
    insertEdges(5, 7, tree);
    insertEdges(5, 8, tree);
    insertEdges(3, 6, tree);
    insertEdges(6, 9, tree);
    
    int []height = new int[N + 1];
    int []vis = new int[N + 1];
    Array.Fill(vis, 0);
    
    height[0] = 0;
    
    // Call the dfs function
    dfs(1, 0, height, vis, tree);
    
    // Function to print
    printLevelsOddEven(N, vis, height);
}
}

// This code is contributed by rutvik_56
Javascript
// JavaScript program to print all levels
// with odd and even number of nodes

// Function for DFS in a tree
function dfs(node, parent, height, vis, tree) {
    // Calculate the level of every node
    height[node] = 1 + height[parent];
    // Mark every node as visited
    vis[node] = 1;
    // Iterate in the subtree
    for (let it = 0; it < tree[node].length; it++) {
        // If the node is not visited
        if (vis[tree[node][it]] == 0) {
            // Call the dfs function
            dfs(tree[node][it], node, height, vis, tree);
        }
    }
}

// Function to insert edges
function insertEdges(x, y, tree) {
    tree[x].push(y);
    tree[y].push(x);
}

// Function to print all levels
function printLevelsOddEven(N, vis, height) {
    let mark = new Array(N + 1);
    mark.fill(0);
    let maxLevel = 0;

    for (let i = 1; i <= N; i++) {
        // Count number of nodes
        // in every level
        if (vis[i] != 0)
            mark[height[i]]++;

        // Find the maximum height of tree
        maxLevel = Math.max(height[i], maxLevel);
    }

    // Print odd number of nodes
    console.log("The levels with odd " +
        "number of nodes are: ");

    for (let i = 1; i <= maxLevel; i++) {
        if (mark[i] % 2 != 0) {
            console.log(i + " ");
        }
    }

    // Print even number of nodes
    console.log("The levels with even " +
        "number of nodes are: ");

    for (let i = 1; i <= maxLevel; i++) {
        if (mark[i] % 2 == 0) {
            console.log(i + " ");
        }
    }
}

// Construct the tree

/*   1
   /   \
  2     3
 / \     \
4    5    6
    / \  /
   7   8 9  */

let N = 9;

let tree = new Array(N + 1);

for (let i = 0; i < N + 1; i++) {
    tree[i] = [];
}

insertEdges(1, 2, tree);
insertEdges(1, 3, tree);
insertEdges(2, 4, tree);
insertEdges(2, 5, tree);
insertEdges(5, 7, tree);
insertEdges(5, 8, tree);
insertEdges(3, 6, tree);
insertEdges(6, 9, tree);

let height = new Array(N + 1);
let vis = new Array(N + 1);
vis.fill(0);

height[0] = 0;

// Call the dfs function
dfs(1, 0, height, vis, tree);

// Function to print
printLevelsOddEven(N, vis, height);

Output
The levels with odd number of nodes are: 1 3 4 
The levels with even number of nodes are: 2 

Complexity Analysis:

  • Time Complexity: O(N) 
  • Auxiliary Space: O(N)

Python Solution(using dequeue):

Approach:

Utilizes a queue (deque from the collections module) to traverse the tree level by level. Each node in the queue is accompanied by its corresponding level.

While traversing the tree, the code counts the number of nodes at each level by incrementing the count in the result list. If the level exceeds the length of the result list, it appends a new entry.

After traversing the tree and counting nodes at each level, it iterates through the counts and identifies levels with odd and even numbers of nodes, storing them in separate lists (odd_levels and even_levels).

C++
#include <iostream>
#include <deque>
#include <vector>

using namespace std;

// Define a class for the tree node
class TreeNode {
public:
    int val;
    vector<TreeNode*> children;

    // Constructor
    TreeNode(int val) {
        this->val = val;
    }
};

// Function to perform level-order traversal and count nodes at each level
vector<int> countNodesAtEachLevel(TreeNode* root) {
    if (!root) {
        return {};
    }

    vector<int> result;
    deque<pair<TreeNode*, int>> queue;  // Tuple contains the node and its level
    queue.push_back({root, 1});

    while (!queue.empty()) {
        TreeNode* node = queue.front().first;
        int level = queue.front().second;
        queue.pop_front();

        if (result.size() < level) {
            result.push_back(0);
        }
        result[level-1]++;

        for (TreeNode* child : node->children) {
            queue.push_back({child, level + 1});
        }
    }

    return result;
}

// Function to print levels with odd and even numbers of nodes
void printLevelsOddEven(vector<int>& counts) {
    vector<int> odd_levels;
    vector<int> even_levels;
    for (int level = 0; level < counts.size(); level++) {
        if (counts[level] % 2 == 1) {
            odd_levels.push_back(level + 1);
        } else {
            even_levels.push_back(level + 1);
        }
    }

    cout << "The levels with odd number of nodes are: ";
    for (int level : odd_levels) {
        cout << level << " ";
    }
    cout << endl;

    cout << "The levels with even number of nodes are: ";
    for (int level : even_levels) {
        cout << level << " ";
    }
    cout << endl;
}

// Driver code
int main() {
    // Construct the tree
    TreeNode* root = new TreeNode(1);
    root->children.push_back(new TreeNode(2));
    root->children.push_back(new TreeNode(3));
    root->children[0]->children.push_back(new TreeNode(4));
    root->children[0]->children.push_back(new TreeNode(5));
    root->children[1]->children.push_back(new TreeNode(6));
    root->children[0]->children[1]->children.push_back(new TreeNode(7));
    root->children[0]->children[1]->children.push_back(new TreeNode(8));
    root->children[1]->children[0]->children.push_back(new TreeNode(9));

    // Perform level-order traversal and count nodes at each level
    vector<int> counts = countNodesAtEachLevel(root);

    // Print levels with odd and even numbers of nodes
    printLevelsOddEven(counts);

    return 0;
}
Java
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;

// Define a class for the tree node
class TreeNode {
    int val;
    List<TreeNode> children;

    TreeNode(int val) {
        this.val = val;
        this.children = new ArrayList<>();
    }
}

public class Main {
    // Function to perform level-order traversal and count nodes at each level
    public static List<Integer> countNodesAtEachLevel(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        if (root == null)
            return result;

        Queue<TreeNode> queue = new ArrayDeque<>();
        queue.add(root);

        while (!queue.isEmpty()) {
            int size = queue.size();
            result.add(size);

            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                for (TreeNode child : node.children) {
                    queue.add(child);
                }
            }
        }

        return result;
    }

    // Function to print levels with odd and even numbers of nodes
    public static void printLevelsOddEven(List<Integer> counts) {
        List<Integer> oddLevels = new ArrayList<>();
        List<Integer> evenLevels = new ArrayList<>();

        for (int level = 0; level < counts.size(); level++) {
            if (counts.get(level) % 2 == 1) {
                oddLevels.add(level + 1);
            } else {
                evenLevels.add(level + 1);
            }
        }

        System.out.println("The levels with odd number of nodes are: " + oddLevels);
        System.out.println("The levels with even number of nodes are: " + evenLevels);
    }

    // Driver code
    public static void main(String[] args) {
        // Construct the tree
        TreeNode root = new TreeNode(1);
        root.children.add(new TreeNode(2));
        root.children.add(new TreeNode(3));
        root.children.get(0).children.add(new TreeNode(4));
        root.children.get(0).children.add(new TreeNode(5));
        root.children.get(1).children.add(new TreeNode(6));
        root.children.get(0).children.get(1).children.add(new TreeNode(7));
        root.children.get(0).children.get(1).children.add(new TreeNode(8));
        root.children.get(1).children.get(0).children.add(new TreeNode(9));

        // Perform level-order traversal and count nodes at each level
        List<Integer> counts = countNodesAtEachLevel(root);

        // Print levels with odd and even numbers of nodes
        printLevelsOddEven(counts);
    }
}
Python3
from collections import deque

# Define a class for the tree node
class TreeNode:
    def __init__(self, val=0, children=None):
        self.val = val
        self.children = children if children is not None else []

# Function to perform level-order traversal and count nodes at each level
def countNodesAtEachLevel(root):
    if not root:
        return []

    result = []
    queue = deque([(root, 1)])  # Tuple contains the node and its level

    while queue:
        node, level = queue.popleft()
        
        if len(result) < level:
            result.append(0)
        result[level-1] += 1

        for child in node.children:
            queue.append((child, level + 1))

    return result

# Function to print levels with odd and even numbers of nodes
def printLevelsOddEven(counts):
    odd_levels = []
    even_levels = []
    for level, count in enumerate(counts, start=1):
        if count % 2 == 1:
            odd_levels.append(level)
        else:
            even_levels.append(level)

    print("The levels with odd number of nodes are:", *odd_levels)
    print("The levels with even number of nodes are:", *even_levels)

# Driver code
if __name__ == "__main__":
    # Construct the tree
    root = TreeNode(1)
    root.children = [TreeNode(2), TreeNode(3)]
    root.children[0].children = [TreeNode(4), TreeNode(5)]
    root.children[1].children = [TreeNode(6)]
    root.children[0].children[1].children = [TreeNode(7), TreeNode(8)]
    root.children[1].children[0].children = [TreeNode(9)]

    # Perform level-order traversal and count nodes at each level
    counts = countNodesAtEachLevel(root)

    # Print levels with odd and even numbers of nodes
    printLevelsOddEven(counts)
JavaScript
// Define a class for the tree node
class TreeNode {
    constructor(val) {
        this.val = val;
        this.children = [];
    }
}

// Function to perform level-order traversal and count nodes at each level
function countNodesAtEachLevel(root) {
    if (!root) {
        return [];
    }

    const result = [];
    const queue = []; // Array to store nodes and their levels
    queue.push({ node: root, level: 1 });

    while (queue.length > 0) {
        const { node, level } = queue.shift();

        if (result.length < level) {
            result.push(0);
        }
        result[level - 1]++;

        for (const child of node.children) {
            queue.push({ node: child, level: level + 1 });
        }
    }

    return result;
}

// Function to print levels with odd and even numbers of nodes
function printLevelsOddEven(counts) {
    const oddLevels = [];
    const evenLevels = [];
    for (let level = 0; level < counts.length; level++) {
        if (counts[level] % 2 === 1) {
            oddLevels.push(level + 1);
        } else {
            evenLevels.push(level + 1);
        }
    }

    console.log("The levels with odd number of nodes are: " + oddLevels.join(" "));
    console.log("The levels with even number of nodes are: " + evenLevels.join(" "));
}

// Driver code
function main() {
    // Construct the tree
    const root = new TreeNode(1);
    root.children.push(new TreeNode(2));
    root.children.push(new TreeNode(3));
    root.children[0].children.push(new TreeNode(4));
    root.children[0].children.push(new TreeNode(5));
    root.children[1].children.push(new TreeNode(6));
    root.children[0].children[1].children.push(new TreeNode(7));
    root.children[0].children[1].children.push(new TreeNode(8));
    root.children[1].children[0].children.push(new TreeNode(9));

    // Perform level-order traversal and count nodes at each level
    const counts = countNodesAtEachLevel(root);

    // Print levels with odd and even numbers of nodes
    printLevelsOddEven(counts);
}

// Calling the main function
main();

Output
The levels with odd number of nodes are: 1 3 4
The levels with even number of nodes are: 2

Time complexity: O(n + h), where n is the number of nodes and h is the height of tree.

Space Complexity: O(h), where h is the height of tree.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads