Open In App

Minimum moves to convert Tree to Star Tree

Last Updated : 22 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given a connected undirected tree with N nodes. In one move, you can merge any two adjacent nodes. Calculate the minimum number of moves required to turn the tree into a star tree:

  •  Merging adjacent nodes means deleting the edge between them and considering both nodes as a single one.
  •  A Star tree is a tree with a central node, and all other nodes are connected to the center node only

Examples:

Input: N = 5, p[] = {-1, 0, 0, 1, 1}
Output: 1
Explanation: 
The tree looks like this:
           0
          / \ 
        1    2 
      /  \ 
     3    4
Merge the edge 0 – 2 in one operation

Input: N = 8, p[] = {-1, 0, 0, 0, 0, 2, 2, 5}
Output: 2
Explanation:
The tree looks like this:
             0
          / / \ \
         / |   |  \
       1   2   3   4
          / \
         5   6
         |
         7
Merge node 5 to 2 and then 2 to 0,   thus tree formed will be a star tree. 

Approach: This can be solved with the following idea:

The approach counts the frequency of each element in the array except for a specified element (e.g. the first element) using an array or HashMap then counts the number of distinct elements in the array by counting the number of non-zero frequency counts and subtracting one if the specified element occurs less than a certain number of times (e.g. less than two times). Return this count.

Below are the steps involved in the implementation of the code:

  • Initialize an array c of size N with all elements set to zero.
  • For i from 1 to N-1, increment the count of the element at index p[i] in the array c.
  • Initialize a variable “ans” to zero.
  • For each element x in the array c, if x is greater than zero, increment “ans” by one.
  • If the count of the first element (i.e. the element at index p[0]) in the array c is less than two, decrement ans by one.
  • Return the maximum of zero and “ans” minus one.

Below is the code implementation of the above approach:

C++




// C++ Implementation
#include <bits/stdc++.h>
using namespace std;
 
// Function to count the minimum
// number of steps required
int solve(int N, int p[])
{
    int c[N] = { 0 };
    for (int i = 1; i < N; i++)
        c[p[i]]++;
 
    int ans = 0;
    for (int x : c)
        ans += (x > 0 ? 1 : 0);
 
    if (c[0] < 2)
        ans--;
 
    // Return the answer
    return max(0, ans - 1);
}
 
// Driver code
int main()
{
 
    int N = 5;
    int p[] = { -1, 0, 0, 1, 1 };
 
    // Function call
    int ans = solve(N, p);
 
    cout << ans << endl;
 
    return 0;
}
// This code is contributed by Tapesh(tapeshdua420)


Java




// Java Implementation
import java.util.*;
 
public class GFG {
 
    // Function to count the minimum
    // number of steps required
    public static int solve(int N, int[] p)
    {
 
        int[] c = new int[N];
        for (int i = 1; i < N; i++)
            c[p[i]]++;
        int ans = 0;
        for (int x : c)
            ans += (x > 0 ? 1 : 0);
        if (c[0] < 2)
            ans--;
 
        // Return the answer
        return Math.max(0, ans - 1);
    }
 
    // Driver code
    public static void main(String[] args)
    {
 
        int N = 5;
        int[] p = { -1, 0, 0, 1, 1 };
 
        // Function call
        int ans = solve(N, p);
 
        System.out.println(ans);
    }
}


Python3




# Python Implementation
def solve(N, p):
    c = [0] * N
    for i in range(1, N):
        c[p[i]] += 1
 
    ans = 0
    for x in c:
        ans += (x > 0)
 
    if c[0] < 2:
        ans -= 1
 
    # Return the answer
    return max(0, ans - 1)
 
 
# Driver code
N = 5
p = [-1, 0, 0, 1, 1]
 
# Function call
ans = solve(N, p)
 
print(ans)
  
# This code is contributed by Tapesh(tapeshdua420)


C#




// C# Implementation
using System;
 
public class GFG
{
    // Function to count the minimum
    // number of steps required
    public static int Solve(int N, int[] p)
    {
        int[] c = new int[N];
        for (int i = 1; i < N; i++)
            c[p[i]]++;
        int ans = 0;
        foreach (int x in c)
            ans += (x > 0 ? 1 : 0);
        if (c[0] < 2)
            ans--;
 
        // Return the answer
        return Math.Max(0, ans - 1);
    }
 
    // Driver code
    public static void Main(string[] args)
    {
        int N = 5;
        int[] p = { -1, 0, 0, 1, 1 };
 
        // Function call
        int ans = Solve(N, p);
 
        Console.WriteLine(ans);
    }
}
 
// This code is contributed by Pushpesh Raj


Javascript




// Javascript Implementation
 
// Function to count the minimum
// number of steps required
function solve(N, p) {
  const c = new Array(N).fill(0);
  for (let i = 1; i < N; i++) {
    c[p[i]]++;
  }
 
  let ans = 0;
  for (const x of c) {
    ans += x > 0 ? 1 : 0;
  }
 
  if (c[0] < 2) {
    ans--;
  }
 
  // Return the answer
  return Math.max(0, ans - 1);
}
 
// Driver code
  const N = 5;
  const p = [-1, 0, 0, 1, 1];
 
  // Function call
  const ans = solve(N, p);
 
  console.log(ans);
 
 
 
//this code is contributed by uttamdp_10


Output

1









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



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads