Skip to content
Related Articles
Open in App
Not now

Related Articles

Find all duplicate levels of given Binary Tree

Improve Article
Save Article
  • Last Updated : 25 Mar, 2022
Improve Article
Save Article

Given the root of a binary tree in which all nodes has values 0 or 1, the task is to find and print all levels for which another level exists such that the decimal representation of each is same. If no such level exists, return an empty list. 

Examples:

Input: 
               1                      
           /      \                   
         0        1                 
       / \       /             
    1    0   1    
        /   \
      0     1
    /
  1
Output:  {3, 1}, {4, 0}
Explanation:  Level 3 is duplicate of level 1
Level 4 is duplicate of level 0

Input: 1
Output: { }

 

Approach: The idea is to solve the problem is based on the following observation:

The idea is to perform levelorder traversal of given Tree and for each level, convert the binary representation to decimal and store in an int variable. Then the problem will be converted to simply find all duplicate elements in given array.

Follow the below steps to solve this problem:

  • Do level order traversal from root to leaf
  • For each level, convert it to decimal equivalent and store the value in a map in {decimal_number, level_number} format.
  • Then, simply check if there are more than one levels for a decimal key. 
  • If yes, then print the levels as duplicates.
  • If no such level exists, return an empty list.

Below is the implementation of the above approach:

C#




// C# program to implement above approach
 
using System;
using System.Collections.Generic;
using System.Linq;
 
// Class containing left and right
// child of current node and key value
public class Node {
    public int data;
    public Node left, right;
    public Node(int item)
    {
        data = item;
        left = right = null;
    }
}
 
public class LevelInfo {
    public int level;
    public int length;
}
 
public class GFG {
 
    // Root of the Binary Tree
    public Node root;
    Dictionary<int, List<LevelInfo> > duplicateMap
        = new Dictionary<int, List<LevelInfo> >();
 
    public virtual List<List<int> >
    printDuplicateLevels(Node root)
    {
        int h = height(root);
        int i;
 
        List<List<int> > dup_levels
            = new List<List<int> >();
 
        // Initialize for the root level
        var zerolevelInfo
            = new LevelInfo() { level = 0,
                                length = 0 };
 
        duplicateMap[root.data]
            = new List<LevelInfo>() { zerolevelInfo };
 
        for (i = 1; i <= h; i++) {
            List<int> currentLevel
                = new List<int>();
            var currentLevelOrder
                = getCurrentLevel(root, i,
                                  currentLevel)
                      .ToList();
 
            int decimalValue = Convert.ToInt32(
                string.Join("", currentLevelOrder), 2);
 
            var currentlevelInfo = new LevelInfo() {
                level = i - 1, length
                               = currentLevelOrder.Count()
            };
 
            if (duplicateMap.ContainsKey(decimalValue)) {
                var dictData
                    = duplicateMap[decimalValue].Where(
                        l => l.length
                            == currentLevelOrder.Count());
                if (dictData.Any()) {
                    List<int> dup_level_curr
                        = new List<int>();
                    dup_level_curr.Add(i - 1);
                    dup_level_curr.Add(
                        dictData.Select(l => l.level)
                            .First());
                    dup_levels.Add(dup_level_curr);
                }
                else {
                    duplicateMap[decimalValue].Add(
                        currentlevelInfo);
                }
            }
            else
                duplicateMap[decimalValue]
                    = new List<LevelInfo>() {
                          currentlevelInfo
                      };
        }
 
        return dup_levels;
    }
 
    // Compute the "height" of a tree
    public virtual int height(Node root)
    {
        if (root == null) {
            return 0;
        }
        else {
 
            // Compute height of each subtree
            int lheight = height(root.left);
            int rheight = height(root.right);
 
            // Use the larger one
            if (lheight > rheight) {
                return (lheight + 1);
            }
            else {
                return (rheight + 1);
            }
        }
    }
 
    // Get nodes at the current level
    public virtual IList<int>
    getCurrentLevel(Node root, int level,
                    List<int> currentLevelOrder)
    {
        if (root == null) {
            return currentLevelOrder;
        }
        if (level == 1) {
            currentLevelOrder.Add(root.data);
        }
        else if (level > 1) {
            getCurrentLevel(root.left, level - 1,
                            currentLevelOrder);
            getCurrentLevel(root.right, level - 1,
                            currentLevelOrder);
        }
        return currentLevelOrder;
    }
 
    // Driver Code
    public static void Main(string[] args)
    {
        GFG tree = new GFG();
        tree.root = new Node(1);
        tree.root.left = new Node(0);
        tree.root.right = new Node(1);
 
        tree.root.left.left = new Node(1);
        tree.root.left.right = new Node(0);
 
        tree.root.right.left = new Node(1);
 
        tree.root.left.right.left = new Node(0);
        tree.root.right.left.right = new Node(1);
 
        tree.root.left.right.left.left = new Node(1);
 
        // Execute and print the duplicate levels
        List<List<int> > dup_levels
            = tree.printDuplicateLevels(tree.root);
 
        Console.Write("[ ");
        foreach(var curr_level in dup_levels)
        {
            Console.Write("[ ");
            foreach(var dupli_level in curr_level)
            {
                Console.Write(dupli_level + " ");
            }
            Console.Write("] ");
        }
        Console.WriteLine("]");
    }
}


Output

[ [ 3 1 ] [ 4 0 ] ]

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


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!