Count pairs of nodes having minimum distance between them equal to the difference of their distances from root
Last Updated :
16 Sep, 2021
Given an N-ary Tree consisting of N nodes valued from [1, N], where node 1 is the root, the task is to count the pairs of nodes having minimum distance between them equal to the difference between the distances of both the nodes from the root.
Examples:
Input: N = 3, Edges[][] = {{1, 2}, {1, 3}}, Below is the Tree:
1
/ \
2 3
Output: 5
Explanation: The following pairs satisfy the conditions: {(1, 1), (2, 2), (3, 3), (2, 1), (3, 1)}.
Input: N = 4, Edges[][] = {{1, 2}, {1, 3}, {2, 4}}, Below is the Tree:
1
/ \
2 3
|
4
Output: 8
Naive Approach: The simplest approach is to find the distance between all possible pairs (i, j) and check for each pair of nodes (i, j), whether distance(i, j) = distance(1, i) - distance(1, j) or not by using Depth-First Search Traversal.
Time Complexity: O(N2)
Auxiliary Space: O(N)
Efficient Approach: The above approach can be optimized based on the following observations:
The minimum distance from node X and the ancestor of node X satisfy the above criteria. Therefore, the task is reduced to finding all the ancestors of every node of the tree.
Follow the steps below to solve the problem:
- Initialize a variable, say ans, to store the count of pairs of nodes.
- Perform a DFS Traversal from the root node with arguments current node, parent node, and depth of node up until the current node.
- Recursively perform DFS Traversal on the child node of every node with the current node as parent node and depth increased by 1.
- In every call, add the depth of the current node to the variable ans.
- After completing the above steps, print the value of ans as the result.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Stores the count of pairs
long long ans = 0;
// Store the adjacency list of
// the connecting vertex
vector<int> adj[int(1e5) + 1];
// Function for theto perform DFS
// traversal of the given tree
void dfsUtil(int u, int par, int depth)
{
// Traverse the adjacency list
// of the current node u
for (auto it : adj[u]) {
// If the current node
// is the parent node
if (it != par) {
dfsUtil(it, u, depth + 1);
}
}
// Add number of ancestors, which
// is same as depth of the node
ans += depth;
}
// Function for DFS traversal of
// the given tree
void dfs(int u, int par, int depth)
{
dfsUtil(u, par, depth);
// Print the result
cout << ans << endl;
}
// Function to find the count of pairs
// such that the minimum distance
// between them is equal to the difference
// between distance of the nodes from root node
void countPairs(vector<vector<int> > edges)
{
for (int i = 0; i < edges.size(); i++) {
int u = edges[i][0];
int v = edges[i][1];
// Add edges to adj[]
adj[u].push_back(v);
adj[v].push_back(u);
}
dfs(1, 1, 1);
}
// Driver Code
int main()
{
vector<vector<int> > edges
= { { 1, 2 }, { 1, 3 }, { 2, 4 } };
countPairs(edges);
return 0;
}
Java
// Java program for the above approach
import java.util.*;
class GFG
{
// Stores the count of pairs
static int ans = 0;
// Store the adjacency list of
// the connecting vertex
static ArrayList<Integer> []adj = new ArrayList[(int)(1e5) + 1];
static{
for(int i = 0; i < adj.length; i++)
adj[i] = new ArrayList<>();
}
// Function for theto perform DFS
// traversal of the given tree
static void dfsUtil(int u, int par, int depth)
{
// Traverse the adjacency list
// of the current node u
for (int it : adj[u]) {
// If the current node
// is the parent node
if (it != par) {
dfsUtil(it, u, depth + 1);
}
}
// Add number of ancestors, which
// is same as depth of the node
ans += depth;
}
// Function for DFS traversal of
// the given tree
static void dfs(int u, int par, int depth)
{
dfsUtil(u, par, depth);
// Print the result
System.out.print(ans +"\n");
}
// Function to find the count of pairs
// such that the minimum distance
// between them is equal to the difference
// between distance of the nodes from root node
static void countPairs(int [][]edges)
{
for (int i = 0; i < edges.length; i++) {
int u = edges[i][0];
int v = edges[i][1];
// Add edges to adj[]
adj[u].add(v);
adj[v].add(u);
}
dfs(1, 1, 1);
}
// Driver Code
public static void main(String[] args)
{
int [][]edges
= { { 1, 2 }, { 1, 3 }, { 2, 4 } };
countPairs(edges);
}
}
// This code is contributed by 29AjayKumar
Python3
# Python3 program for the above approach
# Stores the count of pairs
ans = 0
# Store the adjacency list of
# the connecting vertex
adj = [[] for i in range(10**5+1)]
# Function for theto perform DFS
# traversal of the given tree
def dfsUtil(u, par, depth):
global adj, ans
# Traverse the adjacency list
# of the current node u
for it in adj[u]:
# If the current node
# is the parent node
if (it != par):
dfsUtil(it, u, depth + 1)
# Add number of ancestors, which
# is same as depth of the node
ans += depth
# Function for DFS traversal of
# the given tree
def dfs(u, par, depth):
global ans
dfsUtil(u, par, depth)
# Print result
print (ans)
# Function to find the count of pairs
# such that the minimum distance
# between them is equal to the difference
# between distance of the nodes from root node
def countPairs(edges):
global adj
for i in range(len(edges)):
u = edges[i][0]
v = edges[i][1]
# Add edges to adj[]
adj[u].append(v)
adj[v].append(u)
dfs(1, 1, 1)
# Driver Code
if __name__ == '__main__':
edges = [ [ 1, 2 ], [ 1, 3 ], [ 2, 4 ] ]
countPairs(edges)
# This code is contributed by mohit kumar 29.
C#
// C# program for the above approach
using System;
using System.Collections.Generic;
public class GFG
{
// Stores the count of pairs
static int ans = 0;
// Store the adjacency list of
// the connecting vertex
static List<int> []adj = new List<int>[(int)(1e5) + 1];
// Function for theto perform DFS
// traversal of the given tree
static void dfsUtil(int u, int par, int depth)
{
// Traverse the adjacency list
// of the current node u
foreach (int it in adj[u]) {
// If the current node
// is the parent node
if (it != par) {
dfsUtil(it, u, depth + 1);
}
}
// Add number of ancestors, which
// is same as depth of the node
ans += depth;
}
// Function for DFS traversal of
// the given tree
static void dfs(int u, int par, int depth)
{
dfsUtil(u, par, depth);
// Print the result
Console.Write(ans +"\n");
}
// Function to find the count of pairs
// such that the minimum distance
// between them is equal to the difference
// between distance of the nodes from root node
static void countPairs(int [,]edges)
{
for (int i = 0; i < edges.GetLength(0); i++)
{
int u = edges[i,0];
int v = edges[i,1];
// Add edges to []adj
adj[u].Add(v);
adj[v].Add(u);
}
dfs(1, 1, 1);
}
// Driver Code
public static void Main(String[] args)
{
int [,]edges
= { { 1, 2 }, { 1, 3 }, { 2, 4 } };
for(int i = 0; i < adj.GetLength(0); i++)
adj[i] = new List<int>();
countPairs(edges);
}
}
// This code is contributed by 29AjayKumar
JavaScript
<script>
// Javascript program for the above approach
// Stores the count of pairs
var ans = 0;
// Store the adjacency list of
// the connecting vertex
var adj = Array.from(Array(100001), ()=>Array());
// Function for theto perform DFS
// traversal of the given tree
function dfsUtil(u, par, depth)
{
// Traverse the adjacency list
// of the current node u
adj[u].forEach(it => {
// If the current node
// is the parent node
if (it != par) {
dfsUtil(it, u, depth + 1);
}
});
// Add number of ancestors, which
// is same as depth of the node
ans += depth;
}
// Function for DFS traversal of
// the given tree
function dfs(u, par, depth)
{
dfsUtil(u, par, depth);
// Print the result
document.write( ans + "<br>");
}
// Function to find the count of pairs
// such that the minimum distance
// between them is equal to the difference
// between distance of the nodes from root node
function countPairs(edges)
{
for (var i = 0; i < edges.length; i++) {
var u = edges[i][0];
var v = edges[i][1];
// Add edges to adj[]
adj[u].push(v);
adj[v].push(u);
}
dfs(1, 1, 1);
}
// Driver Code
var edges
= [ [ 1, 2 ], [ 1, 3 ], [ 2, 4 ] ];
countPairs(edges);
// This code is contributed by itsok.
</script>
Time Complexity: O(N)
Auxiliary Space: O(N)
Similar Reads
Count nodes having Bitwise XOR of all edges in their path from the root equal to K Given a Binary Tree consisting of N nodes and two integers R and K. Each edge of the tree has a positive integer associated with it, given in the form {u, v, w} where the edge (u, v) has weight w. The task is to calculate the number of nodes S having Bitwise XOR of all edges in the path from root R
9 min read
Minimum difference between any two weighted nodes in Sum Tree of the given Tree Given a tree of N nodes, the task is to convert the given tree to its Sum Tree(including its own weight) and find the minimum difference between any two node's weight of the sum tree. Note: The N nodes of the given tree are given in the form of top to bottom with N-1 line where each line describes t
11 min read
Count pairs of vertices in Tree such that distance between them is even Given a tree of N vertices, the task is to find the number of pairs of vertices such that the distance between them is even but cannot be 0 Examples: Input: N = 5, Edges = [ [1, 0], [2, 1], [3, 1], [4, 3] ] 0 / 1 / \ 2 3 \ 4 Output: 4Explanation: There are four pairs of vertices such that the distan
15+ min read
Find the number of distinct pairs of vertices which have a distance of exactly k in a tree Given an integer k and a tree with n nodes. The task is to count the number of distinct pairs of vertices that have a distance of exactly k. Examples: Input: k = 2 Output: 4Input: k = 3 Output: 2 Approach: This problem can be solved using dynamic programming. For every vertex v of the tree, we calcu
8 min read
Count of nodes in a given N-ary tree having distance to all leaf nodes equal in their subtree Given an N-ary tree root, the task is to find the number of non-leaf nodes in the tree such that all the leaf nodes in the subtree of the current node are at an equal distance from the current node. Example: Input: Tree in the below imageOutput: 4Explanation: The nodes {10, 3, 2, 4} have the distanc
11 min read
Minimum of the Maximum distances from any node to all other nodes of given Tree Given a tree with N vertices and N-1 edges represented by a 2D array edges[], the task is to find the minimum value among the maximum distances from any node to all other nodes of the tree. Examples: Input: N = 4, edges[] = { {1, 2}, {2, 3}, {2, 4} } Output: 1Explanation: The Tree looks like the fol
8 min read
Count root to leaf paths having exactly K distinct nodes in a Binary Tree Given a Binary Tree consisting of N nodes rooted at 1, an integer K and an array arr[] consisting of values assigned to each node, the task is to count the number of root to leaf paths having exactly K distinct nodes in the given Binary Tree. Examples: Input: N = 3, Edges[][] = {{1, 2}, {1, 3}}, arr
11 min read
Distance between two nodes of binary tree with node values from 1 to N Given a binary tree with 1 as its root and for any parent i its left child will be 2*i and right child will be 2*i+1. The task is to find the minimum distance between two nodes n1 and n2. 1 / \ 2 3 / \ / \ 4 5 6 7 / \ / \ / \ / \ . . . . . . . . Examples: Input : n1 = 7, n2 = 10 Output : 5 Input : n
7 min read
Sum of the distances from every node to all other nodes is maximum Given a tree with N nodes and N-1 edges with root at 1 and given an array of N-1 integers. The task is to assign weights to the edges in the tree such that the sum of the distances from every node to all other nodes is maximum. Examples: Input: Output: 46 Assign the edge 1-2 with weight 5 Assign the
14 min read
Queries to find distance between two nodes of a Binary tree - O(logn) method Given a binary tree, the task is to find the distance between two keys in a binary tree, no parent pointers are given. Distance between two nodes is the minimum number of edges to be traversed to reach one node from other. This problem has been already discussed in previous post but it uses three tr
15+ min read