The Wayback Machine - https://web.archive.org/web/20241004141238/https://www.geeksforgeeks.org/construct-tree-from-ancestor-matrix/
Open In App

Construct tree from ancestor matrix

Last Updated : 20 Feb, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given an ancestor matrix mat[n][n] where Ancestor matrix is defined as below. 

mat[i][j] = 1 if i is ancestor of j
mat[i][j] = 0, otherwise

Construct a Binary Tree from a given ancestor matrix where all its values of nodes are from 0 to n-1.

  1. It may be assumed that the input provided in the program is valid and the tree can be constructed out of it.
  2. Many Binary trees can be constructed from one input. The program will construct any one of them.

Examples: 

Input: 0 1 1
       0 0 0 
       0 0 0 
Output: Root of one of the below trees.
    0                0
  /   \     OR     /   \
 1     2          2     1

Input: 0 0 0 0 0 0 
       1 0 0 0 1 0 
       0 0 0 1 0 0 
       0 0 0 0 0 0 
       0 0 0 0 0 0 
       1 1 1 1 1 0
Output: Root of one of the below trees.
      5              5               5
   /    \           / \            /   \
  1      2   OR    2   1    OR    1     2  OR ....
 /  \   /        /    /  \       / \    /
0   4  3        3    0    4     4   0  3
There are different possible outputs because ancestor
matrix doesn't store that which child is left and which
is right.

We strongly recommend you to minimize your browser and try this yourself first. 

Observations used in the solution: 

  1. The rows that correspond to leaves have all 0’s
  2. The row that corresponds to root has maximum number of 1’s.
  3. Count of 1’s in i’th row indicates number of descendants of node i.

The idea is to construct the tree in bottom up manner.

  1. Create an array of node pointers node[].
  2. Store row numbers that correspond to a given count. We have used multimap for this purpose.
  3. Process all entries of multimap from smallest count to largest (Note that entries in map and multimap can be traversed in sorted order). Do following for every entry.
    • Create a new node for current row number.
    • If this node is not a leaf node, consider all those descendants of it whose parent is not set, make current node as its parent.
  4. The last processed node (node with maximum sum) is root of tree.

Below is the implementation of the above approach:

C++




// Given an ancestor matrix for binary tree, construct
// the tree.
#include <bits/stdc++.h>
using namespace std;
   
# define N 6
   
/* A binary tree node */
struct Node
{
    int data;
    Node *left, *right;
};
   
/* Helper function to create a new node */
Node* newNode(int data)
{
    Node* node = new Node;
    node->data = data;
    node->left = node->right = NULL;
    return (node);
}
   
// Constructs tree from ancestor matrix
Node* ancestorTree(int mat[][N])
{
    // Binary array to determine whether
    // parent is set for node i or not
    int parent[N] = {0};
   
    // Root will store the root of the constructed tree
    Node* root = NULL;
   
    // Create a multimap, sum is used as key and row
    // numbers are used as values
    multimap<int, int> mm;
   
    for (int i = 0; i < N; i++)
    {
        int sum = 0; // Initialize sum of this row
        for (int j = 0; j < N; j++)
            sum += mat[i][j];
   
        // insert(sum, i) pairs into the multimap
        mm.insert(pair<int, int>(sum, i));
    }
   
    // node[i] will store node for i in constructed tree
    Node* node[N];
   
    // Traverse all entries of multimap.  Note that values
    // are accessed in increasing order of sum
    for (auto it = mm.begin(); it != mm.end(); ++it)
    {
      // create a new node for every value
      node[it->second] = newNode(it->second);
   
      // To store last processed node. This node will be
      // root after loop terminates
      root = node[it->second];
   
      // if non-leaf node
      if (it->first != 0)
      {
        // traverse row 'it->second' in the matrix
        for (int i = 0; i < N; i++)
        {
           // if parent is not set and ancestor exits
           if (!parent[i] && mat[it->second][i])
           {
             // check for unoccupied left/right node
             // and set parent of node i
             if (!node[it->second]->left)
               node[it->second]->left = node[i];
             else
               node[it->second]->right = node[i];
   
             parent[i] = 1;
           }
        }
      }
    }
    return root;
}
   
/* Given a binary tree, print its nodes in inorder */
void printInorder(Node* node)
{
    if (node == NULL)
        return;
    printInorder(node->left);
    printf("%d ", node->data);
    printInorder(node->right);
}
   
// Driver code
int main()
{
    int mat[N][N] = {{ 0, 0, 0, 0, 0, 0 },
        { 1, 0, 0, 0, 1, 0 },
        { 0, 0, 0, 1, 0, 0 },
        { 0, 0, 0, 0, 0, 0 },
        { 0, 0, 0, 0, 0, 0 },
        { 1, 1, 1, 1, 1, 0 }
    };
   
    Node* root = ancestorTree(mat);
   
    cout << "Inorder traversal of tree is \n";
     
    // Function call
    printInorder(root);
   
    return 0;
}


Java




// Given an ancestor matrix for binary tree, construct
// the tree.
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;
 
/* A binary tree node */
class Node {
    int data;
    Node left, right;
 
    Node(int d)
    {
        data = d;
        left = right = null;
    }
}
 
public class TreeFromAncestorMatrix {
 
    static Node ancestorNode(int[][] mat)
    {
        int n = mat.length;
 
        // Binary array to determine whether parent is set
        // for node i or not
        int[] parent = new int[n];
        Node root = null;
 
        // Map to store row numbers as key and
        // their sum as their values
        Map<Integer, Integer> map = new HashMap<>();
 
        for (int i = 0; i < n; i++) {
            int sum = 0;
 
            for (int j = 0; j < n; j++)
                sum += mat[i][j];
 
            map.put(i, sum);
        }
 
        // node[i] will store node for i in
        //constructed tree
        Node node[] = new Node[n];
 
        // Sorting the map according to its
        //values
        Map<Integer, Integer> sorted
            = map.entrySet()
                  .stream()
                  .sorted(Map.Entry.comparingByValue())
                  .collect(Collectors.toMap(
                      e
                      -> e.getKey(),
                      e
                      -> e.getValue(),
                      (e1, e2) -> e2, LinkedHashMap::new));
 
        // Traverse all entries of sorted Map.
        // Note that values are accessed in increasing order
        // of sum
        for (Map.Entry<Integer, Integer> entry :
             sorted.entrySet()) {
            int key = entry.getKey();
            int value = entry.getValue();
 
            // create a new node for every
            // value
            node[key] = new Node(key);
 
            // if it is an internal node
            if (value != 0) {
 
                // Traverse row
                //corresponding to the node
                for (int i = 0; i < n; i++)
                {
 
                    // if parent is not set and
                    //ancestor exits
                    if (parent[i] == 0
                        && mat[key][i] != 0)
                    {
                        // check for unoccupied
                        // left/right node and
                        //set parent of node i
                        if (node[key].left == null)
                            node[key].left = node[i];
                        else
                            node[key].right = node[i];
                        parent[i] = 1;
                    }
 
                    // To store last processed
                    // node. This node will be root after
                    // loop terminates
                    root = node[key];
                }
            }
        }
 
        return root;
    }
  
    /* Given a binary tree, print its nodes in inorder */
    static void inOrder(Node root)
    {
        if (root == null)
            return;
        inOrder(root.left);
        System.out.print(root.data + " ");
        inOrder(root.right);
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int mat[][] = {
            { 0, 0, 0, 0, 0, 0 }, { 1, 0, 0, 0, 1, 0 },
            { 0, 0, 0, 1, 0, 0 }, { 0, 0, 0, 0, 0, 0 },
            { 0, 0, 0, 0, 0, 0 }, { 1, 1, 1, 1, 1, 0 }
        };
 
        Node root = ancestorNode(mat);
 
         // Function call
        inOrder(root);
    }
}
 
// contribute by amarsomani


Python3




# key structure to store a binary tree node
class Node:
    def __init__(self, key, left = None, right = None):
        self.key = key
        self.left = left
        self.right = right
 
# Utility function to print binary tree nodes in-order fashion
def inorder(node):
    if node:
        inorder(node.left)
        print(node.key, end = ' ')
        inorder(node.right)
 
# Function to construct a binary tree
# from specified ancestor matrix
def constructBT(mat):
   
    # get number of rows in the matrix
    N = len(mat)
 
    # create an empty multi-dict
    dict = {}
 
    # Use sum as key and row numbers as values in the multi-dict
    for i in range(N):
 
        # find the sum of the current row
        total = sum(mat[i])
 
        # insert the sum and row number into the dict
        dict.setdefault(total, []).append(i)
 
    # node[i] will store node for i in constructed tree
    node = [Node(-1)] * N
    last = 0
 
    # the value of parent[i] is true if parent is set for i'th node
    parent = [False] * N
 
    # Traverse the dictionary in sorted order (default behavior)
    for key in dict.keys():
        for row in dict.get(key):
            last = row
             
            # create a new node
            node[row] = Node(row)
 
            # if leaf node, do nothing
            if key == 0:
                continue
 
            # traverse row
            for i in range(N):
               
                # do if parent is not set and ancestor exits
                if not parent[i] and mat[row][i] == 1:
                   
                    # check for the unoccupied node
                    if node[row].left is None:
                        node[row].left = node[i]
                    else:
                        node[row].right = node[i]
 
                    # set parent for i'th node
                    parent[i] = True
 
    # last processed node is the root
    return node[last]
 
# Construct a Binary Tree from Ancestor Matrix
if __name__ == '__main__':
 
    mat = [[0, 0, 0, 0, 0, 0],
        [1, 0, 0, 0, 1, 0],
        [0, 0, 0, 1, 0, 0],
        [0, 0, 0, 0, 0, 0],
        [0, 0, 0, 0, 0, 0],
        [1, 1, 1, 1, 0, 0]]
 
    root = constructBT(mat)
    inorder(root)
 
# This code is contributed by Priyadarshini Kumari


C#




// Given an ancestor matrix for binary tree, construct
// the tree.
using System;
using System.Collections.Generic;
using System.Linq;
 
/* A binary tree node */
public
  class Node
  {
    public
      int data;
    public
      Node left, right;
    public
      Node(int d)
    {
      data = d;
      left = right = null;
    }
  }
 
public class TreeFromAncestorMatrix
{
 
  static Node ancestorNode(int[,] mat)
  {
    int n = mat.GetLength(0);
 
    // Binary array to determine whether parent is set
    // for node i or not
    int[] parent = new int[n];
    Node root = null;
 
    // Map to store row numbers as key and
    // their sum as their values
    Dictionary<int, int> map = new Dictionary<int, int>();
    for (int i = 0; i < n; i++)
    {
      int sum = 0;
      for (int j = 0; j < n; j++)
        sum += mat[i, j];
      map.Add(i, sum);
    }
 
    // node[i] will store node for i in
    //constructed tree
    Node []node = new Node[n];
 
    var sorted = from entry in map orderby entry.Value ascending select entry;
 
    // Traverse all entries of sorted Map.
    // Note that values are accessed in increasing order
    // of sum
    foreach (KeyValuePair<int, int> entry in
             sorted)
    {
      int key = entry.Key;
      int value = entry.Value;
 
      // create a new node for every
      // value
      node[key] = new Node(key);
 
      // if it is an internal node
      if (value != 0)
      {
 
        // Traverse row
        //corresponding to the node
        for (int i = 0; i < n; i++)
        {
 
          // if parent is not set and
          //ancestor exits
          if (parent[i] == 0
              && mat[key,i] != 0)
          {
            // check for unoccupied
            // left/right node and
            //set parent of node i
            if (node[key].left == null)
              node[key].left = node[i];
            else
              node[key].right = node[i];
            parent[i] = 1;
          }
 
          // To store last processed
          // node. This node will be root after
          // loop terminates
          root = node[key];
        }
      }
    }
    return root;
  }
 
  /* Given a binary tree, print its nodes in inorder */
  static void inOrder(Node root)
  {
    if (root == null)
      return;
    inOrder(root.left);
    Console.Write(root.data + " ");
    inOrder(root.right);
  }
 
  // Driver code
  public static void Main(String[] args)
  {
    int [,]mat = {
      { 0, 0, 0, 0, 0, 0 }, { 1, 0, 0, 0, 1, 0 },
      { 0, 0, 0, 1, 0, 0 }, { 0, 0, 0, 0, 0, 0 },
      { 0, 0, 0, 0, 0, 0 }, { 1, 1, 1, 1, 1, 0 }
    };
    Node root = ancestorNode(mat);
 
    // Function call
    inOrder(root);
  }
}
 
// This code is contributed by Rajput-Ji


Javascript




<script>
 
// Given an ancestor matrix for binary tree, construct
// the tree.
 
/* A binary tree node */
class Node
{
  constructor(d)
  {
    this.data = d;
    this.left = null;
    this.right = null;
  }
}
 
 function ancestorNode( mat)
{
  var n = mat.length;
   
  // Binary array to determine whether parent is set
  // for node i or not
  var parent = Array(n).fill(0);
  var root = null;
   
  // Map to store row numbers as key and
  // their sum as their values
  var map = new Map();
 
  for(var i = 0; i < n; i++)
  {
    var sum = 0;
    for (var j = 0; j < n; j++)
      sum += mat[i][j];
    map.set(i, sum);
  }
   
  // node[i] will store node for i in
  //constructed tree
  var node = Array(n).fill(null);
 
  // Traverse all entries of sorted Map.
  // Note that values are accessed in increasing order
  // of sum
  for(var data of [...map].sort((a,b)=> a[1]-b[1]))
  {
    
    var key = data[0];
    var value = data[1];
 
    // create a new node for every
    // value
    node[key] = new Node(key);
     
    // if it is an internal node
    if (value != 0)
    {
     
      // Traverse row
      //corresponding to the node
      for (var i = 0; i < n; i++)
      {
       
        // if parent is not set and
        //ancestor exits
        if (parent[i] == 0
            && mat[key][i] != 0)
        {
         
          // check for unoccupied
          // left/right node and
          //set parent of node i
          if (node[key].left == null)
            node[key].left = node[i];
          else
            node[key].right = node[i];
          parent[i] = 1;
        }
         
        // To store last processed
        // node. This node will be root after
        // loop terminates
        root = node[key];
      }
    }
  };
 
  return root;
}
 
/* Given a binary tree, print its nodes in inorder */
function inOrder(root)
{
  if (root == null)
    return;
  inOrder(root.left);
  document.write(root.data + " ");
  inOrder(root.right);
}
 
// Driver code
var mat = [
  [ 0, 0, 0, 0, 0, 0 ], [ 1, 0, 0, 0, 1, 0 ],
  [ 0, 0, 0, 1, 0, 0 ], [ 0, 0, 0, 0, 0, 0 ],
  [ 0, 0, 0, 0, 0, 0 ], [ 1, 1, 1, 1, 1, 0 ]
];
var root = ancestorNode(mat);
 
// Function call
inOrder(root);
 
// This code is contributed by rdtank.
</script>


Output

0 1 4 5 3 2

Time Complexity: O(N2), where N is the number of nodes in the tree.
Space Complexity: O(N2), where N is the number of nodes in the tree.

Note that we can also use an array of vectors in place of multimap. We have used multimap for simplicity. Array of vectors would improve performance as inserting and accessing elements would take O(1) time.



Previous Article
Next Article

Similar Reads

Construct Binary Tree from Ancestor Matrix | Top Down Approach
Given an ancestor matrix mat[n][n] where the ancestor matrix is defined as below. mat[i][j] = 1 if i is ancestor of j mat[i][j] = 0, otherwise Construct a Binary Tree from the given ancestor matrix where all its values of nodes are from 0 to n-1. It may be assumed that the input provided by the program is valid and the tree can be constructed out o
10 min read
Construct Ancestor Matrix from a Given Binary Tree
Given a Binary Tree where all values are from 0 to n-1. Construct an ancestor matrix mat[n][n]. Ancestor matrix is defined as below. mat[i][j] = 1 if i is ancestor of j mat[i][j] = 0, otherwise Examples: Input: Root of below Binary Tree. 0 / \ 1 2 Output: 0 1 1 0 0 0 0 0 0 Input: Root of below Binary Tree. 5 / \ 1 2 / \ / 0 4 3 Output: 0 0 0 0 0 0
15 min read
Lowest Common Ancestor in a Binary Tree | Set 3 (Using RMQ)
Given a rooted tree, and two nodes are in the tree, find the Lowest common ancestor of both the nodes. The LCA for two nodes u and v is defined as the farthest node from the root that is the ancestor to both u and v. Prerequisites: LCA | SET 1 Example for the above figure : Input : 4 5 Output : 2 Input : 4 7 Output : 1 Converting LCA to RMQ(Range M
15+ min read
K-th ancestor of a node in Binary Tree | Set 3
Given a binary tree in which nodes are numbered from 1 to N. Given a node and a positive integer K. We have to print the Kth ancestor of the given node in the binary tree. If there does not exist any such ancestor then print -1.For example in the below given binary tree, 2nd ancestor of node 4 and 5 is 1. 3rd ancestor of node 4 will be -1. Approach
7 min read
Kth ancestor of a node in an N-ary tree using Binary Lifting Technique
Given a vertex V of an N-ary tree and an integer K, the task is to print the Kth ancestor of the given vertex in the tree. If there does not exist any such ancestor then print -1.Examples: Input: K = 2, V = 4 Output: 1 2nd parent of vertex 4 is 1.Input: K = 3, V = 4 Output: -1 Approach: The idea is to use Binary Lifting Technique. This technique is
9 min read
Least Common Ancestor of any number of nodes in Binary Tree
Given a binary tree (not a binary search tree) and any number of Key Nodes, the task is to find the least common ancestor of all the key Nodes. Following is the definition of LCA from Wikipedia: Let T be a rooted tree. The lowest common ancestor between two nodes n1 and n2 is defined as the lowest node in T that has both n1 and n2 as descendants (w
9 min read
Lowest Common Ancestor for a Set of Nodes in a Rooted Tree
Given a rooted tree with N nodes, the task is to find the Lowest Common Ancestor for a given set of nodes V of that tree. Examples: Input: 1 / | \ 2 3 4 / \ | | 5 6 7 10 / \ 8 9 V[] = {7, 3, 8, 9} Output: 3 Input: 1 / | \ 2 3 4 / \ | | 5 6 7 10 / \ 8 9 V[] = {4, 6, 7} Output: 1 Approach: We can observe that the Lowest Common Ancestors for any set o
12 min read
Lowest Common Ancestor of the deepest leaves of a Binary Tree
Given a Binary Tree consisting of N nodes having distinct values from the range [1, N], the task is to find the lowest common ancestor of the deepest leaves of the binary tree. Examples: Input: Output: 1Explanation: The deepest leaf nodes of the tree are {8, 9, 10}. Lowest common ancestor of these nodes is 1. Input: Output: 6 Approach: The given pr
10 min read
Maximize difference between pair of nodes in a given rooted tree such that one node is ancestor of another
Given a Generic Tree consisting of N nodes valued from 0 to (N - 1) where P[i]th in the array P[] denotes ith nodes parent(1-based indexing). Each ith node has a weight attached to it, given in the array W[]. The task is to find a pair of nodes (u, v), such that u is an ancestor of v, and Wu - Wv is maximized. Note: In the array P[], -1 denotes the
14 min read
Maximum difference between node and its ancestor in Binary Tree
Given a Binary tree, The task is to find the maximum value by subtracting the value of node B from the value of node A, where A and B are two nodes of the binary tree and A is an ancestor of B. Examples: Input: Output: 7Explanation: We can have various ancestor-node difference, some of which are given below : 8 – 3 = 5 , 3 – 7 = -4, 8 – 1 = 7, 10 –
10 min read
Lowest Common Ancestor in a Binary Tree using Parent Pointer
Given values of two nodes in a Binary Tree, find the Lowest Common Ancestor (LCA). It may be assumed that both nodes exist in the tree. For example, consider the Binary Tree in diagram, LCA of 10 and 14 is 12 and LCA of 8 and 14 is 8. Let T be a rooted tree. The lowest common ancestor between two nodes n1 and n2 is defined as the lowest node in T t
15+ min read
Query for ancestor-descendant relationship in a tree
Given a rooted tree with N vertices and N-1 edges. We will be given many pairs of vertices u and v, we need to tell whether u is an ancestor of v or not. Given tree will be rooted at the vertex with index 0. Examples: u = 1 v = 6 we can see from above tree that node 1 is ancestor of node 6 so the answer will be yes. u = 1 v = 7 we can see from abov
9 min read
Kth ancestor of a node in binary tree | Set 2
Given a binary tree in which nodes are numbered from 1 to n. Given a node and a positive integer K. We have to print the Kth ancestor of the given node in the binary tree. If there does not exist any such ancestor then print -1.For example in the below given binary tree, the 2nd ancestor of 5 is 1. 3rd ancestor of node 5 will be -1.   We have discu
7 min read
Lowest Common Ancestor in a Binary Tree
Given two nodes n1 and n2, The Lowest Common Ancestor (or LCA) is the lowest node in the tree that has both n1 and n2 as descendants. In other words, LCA of n1 and n2 is the shared ancestor of n1 and n2 that is located farthest from the root.  For example, consider the below tree LCA of 4 and 5 is 2LCA of 5 and 6 is 1LCA of 7 and 2 is 1 Using Array
15+ min read
LCA in BST - Lowest Common Ancestor in Binary Search Tree
Given two values n1 and n2 in a Binary Search Tree, find the Lowest Common Ancestor (LCA). You may assume that both values exist in the tree. The lowest common ancestor between two nodes n1 and n2 is defined as the lowest node that has both n1 and n2 as descendants (where we allow a node to be a descendant of itself). In other words, the LCA of n1
15+ min read
K-th ancestor of a node in Binary Tree
Given a binary tree in which nodes are numbered from 1 to n. Given a node and a positive integer K. We have to print the K-th ancestor of the given node in the binary tree. If there does not exist any such ancestor then print -1.For example in the below given binary tree, 2nd ancestor of node 4 and 5 is 1. 3rd ancestor of node 4 will be -1. The ide
15+ min read
Construct a square Matrix whose parity of diagonal sum is same as size of matrix
Given an integer N representing the size of the matrix, the task is to construct a square matrix N * N which have an element from 1 to N2 such that the parity of the sum of its diagonals is equal to the parity of integer N. Examples: Input: N = 4Output:1 2 3 4 8 7 6 59 10 11 1216 15 14 13Explanation:Sum of diagonal = 32 and 36 and integer N = 4, al
6 min read
Construct a Matrix such that each cell consists of sum of adjacent elements of respective cells in given Matrix
Given a matrix arr[][] of dimensions N * M, the task is to generate a matrix such that any cell (r, c) stores the sum of adjacent elements present horizontally, vertically, and diagonally in the given matrix. Examples: Input: arr[][] = {{1, 3}, {2, 4}}Output: {{9, 7}, {8, 6}}Explanation: Matrix is constructed by the following operations: For cell (
9 min read
Circular Matrix (Construct a matrix with numbers 1 to m*n in spiral way)
Given two values m and n, fill a matrix of size 'm*n' in a spiral (or circular) fashion (clockwise) with natural numbers from 1 to m*n. Examples: Input : m = 4, n = 4 Output : 1 2 3 4 12 13 14 5 11 16 15 6 10 9 8 7 Input : m = 3, n = 4 Output : 1 2 3 4 10 11 12 5 9 8 7 6 The idea is based on Print a given matrix in spiral form. We create a matrix o
10 min read
Construct XOR tree by Given leaf nodes of Perfect Binary Tree
Given the leaf nodes of a perfect binary tree, the task is to construct the XOR tree and print the root node of this tree. An XOR tree is a tree whose parent node is the XOR of the left child and the right child node of the tree. Parent node = Left child node ^ Right child node Examples: Input: arr = {40, 32, 12, 1, 4, 3, 2, 7} Output: Nodes of the
12 min read
Construct Full Binary Tree using its Preorder traversal and Preorder traversal of its mirror tree
Given two arrays that represent Preorder traversals of a full binary tree and its mirror tree, we need to write a program to construct the binary tree using these two Preorder traversals.A Full Binary Tree is a binary tree where every node has either 0 or 2 children. Note: It is not possible to construct a general binary tree using these two traver
12 min read
Lowest Common Ancestor in Parent Array Representation
Given a binary tree represented as parent array, find Lowest Common Ancestor between two nodes 'm' and 'n'. In the above diagram, LCA of 10 and 14 is 12 and LCA of 10 and 12 is 12. Make a parent array and store the parent of ith node in it. Parent of root node should be -1. Now, access all the nodes from the desired node 'm' till root node and mark
6 min read
Minimum number of groups of nodes such that no ancestor is present in the same group
Given a tree of N nodes. The task is to form the minimum number of groups of nodes such that every node belong to exactly one group, and none of its ancestors are in the same group. The parent of each node is given (-1 if a node does not have a parent).Examples: Input: par[] = {-1, 1, 2, 1, 4} Output: 3 The three groups can be: Group 1: {1} Group 2
6 min read
Maximum difference between node and its ancestor in a Directed Acyclic Graph ( DAG )
Given a 2D array Edges[][], representing a directed edge between the pair of nodes in a Directed Acyclic Connected Graph consisting of N nodes valued from [1, N] and an array arr[] representing weights of each node, the task is to find the maximum absolute difference between the weights of any node and any of its ancestors. Examples: Input: N = 5,
8 min read
Level Ancestor Problem
The level ancestor problem is the problem of preprocessing a given rooted tree T into a data structure that can determine the ancestor of a given node at a given depth from the root of the tree. Here depth of any node in a tree is the number of edges on the shortest path from the root of the tree to the node. Given tree is represented as un-directe
15+ min read
Construct a matrix such that union of ith row and ith column contains every element from 1 to 2N-1
Given a number N, the task is to construct a square matrix of N * N where the union of elements in some ith row with the ith column contains every element in the range [1, 2*N-1]. If no such matrix exists, print -1.Note: There can be multiple possible solutions for a particular N Examples: Input: N = 6 Output: 6 4 2 5 3 1 10 6 5 3 1 2 8 11 6 1 4 3
11 min read
Construct a Doubly linked linked list from 2D Matrix
Given a 2D matrix, the task is to convert it into a doubly-linked list with four pointers that are next, previous, up, and down, each node of this list should be connected to its next, previous, up, and down nodes.Examples: Input: 2D matrix 1 2 3 4 5 6 7 8 9 Output: Approach: The main idea is to construct a new node for every element of the matrix
15+ min read
Construct a Matrix of size NxN with values in range [1, N^2] as per given conditions
Content Removed. Please refer Matrix Category for such problems.t
1 min read
Construct a matrix with sum equal to the sum of diagonal elements
Given an integer N, the task is to construct a matrix of size N2 using positive and negative integers and excluding 0, such that the sum of the matrix is equal to the sum of the diagonal of the matrix. Examples: Input: N = 2 Output: 1 -2 2 4 Explanation: Diagonal sum = (1 + 4) = 5 Matrix sum = (1 - 2 + 2 + 4) = 5 Input: N = 5 Output: 1 2 3 5 10 3 1
4 min read
Construct a Matrix N x N with first N^2 natural numbers for an input N
Given an integer N, the task is to construct a matrix M[][] of size N x N with numbers in the range [1, N^2] with the following conditions : The elements of the matrix M should be an integer between 1 and N^2.All elements of the matrix M are pairwise distinct.For each square submatrix containing cells in row r through r+a and in columns c through c
6 min read
Article Tags :
Practice Tags :