Count ancestors with smaller value for each node of a Binary Tree
Last Updated :
01 Jun, 2021
Given a Binary Tree consisting of N nodes, valued from 1 to N, rooted at node 1, the task is for each node is to count the number of ancestors with a value smaller than that of the current node.
Examples:
Input: Below is the given Tree:
1
/ \
4 5
/ /\
6 3 2
Output: 0 1 1 1 1 2
Explanation:
Since node 1 is the root node, it has no ancestors.
Ancestors of node 2: {1, 5}. Number of ancestors having value smaller than 2 is 1.
Ancestors of node 3: {1, 5}. Number of ancestors having value smaller than 3 is 1.
Ancestors of node 4: {1}. Number of ancestors having value smaller than 4 is 1.
Ancestors of node 5: {1}. Number of ancestors having value smaller than 5 is 1.
Ancestors of node 6: {1, 4}. Number of ancestors having value smaller than 6 is 2.
Input: Below is the given Tree:
1
/ \
3 2
\
4
Output: 0 1 1 2
Explanation:
Node 1 has no ancestors.
Ancestors of node 2: {1}. Number of ancestors having value smaller than 2 is 1.
Ancestors of node 3: {1}. Number of ancestors having value smaller than 3 is 1.
Ancestors of node 4: {1, 2}. Number of ancestors having value smaller than 4 is 2.
Approach: The idea is to perform DFS traversal from the root node of the Tree and store the immediate parent of each node in an array. Then iterate over each node and using the parent array, compare its value with all its ancestors. Finally, print the result.
Follow the steps below to solve the problem:
- Initialize an array, say par[] of size N, with -1, to store the immediate parent of each node.
- Perform DFS traversal from the root node and perform the following steps:
- Update the parent of the current node.
- Recursively call the children of the current node.
- Now, iterate over the range [1, N] using a variable i and perform the following steps:
- Store the current node in a variable, say node.
- Iterate while par[node] is not equal to -1:
- If par[node] is less than i, then increment cnt by 1.
- Update node as par[node].
- After completing the above steps, print the value of cnt as the value for the current node.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void add_edge(vector< int > adj[],
int u, int v)
{
adj[u].push_back(v);
adj[v].push_back(u);
}
void dfs(vector< int >& parent,
vector< int > adj[],
int u,
int par = -1)
{
parent[u] = par;
for ( auto child : adj[u]) {
if (child != par)
dfs(parent, adj, child, u);
}
}
void countSmallerAncestors(
vector< int > adj[], int n)
{
vector< int > parent( int (1e5), 0);
dfs(parent, adj, 1);
for ( int i = 1; i <= n; i++) {
int node = i;
int cnt = 0;
while (parent[node] != -1) {
if (parent[node] < i)
cnt += 1;
node = parent[node];
}
cout << cnt << " " ;
}
}
int main()
{
int N = 6;
vector< int > adj[ int (1e5)];
add_edge(adj, 1, 5);
add_edge(adj, 1, 4);
add_edge(adj, 4, 6);
add_edge(adj, 5, 3);
add_edge(adj, 5, 2);
countSmallerAncestors(adj, N);
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG{
static void add_edge(ArrayList<ArrayList<Integer>> adj,
int u, int v)
{
adj.get(u).add(v);
adj.get(v).add(u);
}
static void dfs(ArrayList<Integer> parent,
ArrayList<ArrayList<Integer>> adj,
int u, int par)
{
parent.set(u,par);
for ( int child : adj.get(u))
{
if (child != par)
dfs(parent, adj, child, u);
}
}
static void countSmallerAncestors(
ArrayList<ArrayList<Integer>> adj, int n)
{
ArrayList<Integer> parent = new ArrayList<Integer>();
for ( int i = 0 ; i < ( int )(1e5); i++)
{
parent.add( 0 );
}
dfs(parent, adj, 1 , - 1 );
for ( int i = 1 ; i <= n; i++)
{
int node = i;
int cnt = 0 ;
while (parent.get(node) != - 1 )
{
if (parent.get(node) < i)
cnt += 1 ;
node = parent.get(node);
}
System.out.print(cnt + " " );
}
}
public static void main (String[] args)
{
int N = 6 ;
ArrayList<ArrayList<Integer>> adj = new ArrayList<ArrayList<Integer>>();
for ( int i = 0 ; i < ( int )(1e5); i++)
{
adj.add( new ArrayList<Integer>());
}
add_edge(adj, 1 , 5 );
add_edge(adj, 1 , 4 );
add_edge(adj, 4 , 6 );
add_edge(adj, 5 , 3 );
add_edge(adj, 5 , 2 );
countSmallerAncestors(adj, N);
}
}
|
Python3
def add_edge(u, v):
global adj
adj[u].append(v)
adj[v].append(u)
def dfs(u, par = - 1 ):
global adj, parent
parent[u] = par
for child in adj[u]:
if (child ! = par):
dfs(child, u)
def countSmallerAncestors(n):
global parent, adj
dfs( 1 )
for i in range ( 1 , n + 1 ):
node = i
cnt = 0
while (parent[node] ! = - 1 ):
if (parent[node] < i):
cnt + = 1
node = parent[node]
print (cnt, end = " " )
if __name__ = = '__main__' :
N = 6
adj = [[] for i in range ( 10 * * 5 )]
parent = [ 0 ] * ( 10 * * 5 )
add_edge( 1 , 5 )
add_edge( 1 , 4 )
add_edge( 4 , 6 )
add_edge( 5 , 3 )
add_edge( 5 , 2 )
countSmallerAncestors(N)
|
C#
using System;
using System.Collections.Generic;
class GFG {
static void add_edge(List<List< int >> adj, int u, int v)
{
adj[u].Add(v);
adj[v].Add(u);
}
static void dfs(List< int > parent,
List<List< int >> adj,
int u,
int par = -1)
{
parent[u] = par;
foreach ( int child in adj[u]) {
if (child != par)
dfs(parent, adj, child, u);
}
}
static void countSmallerAncestors(
List<List< int >> adj, int n)
{
List< int > parent = new List< int >();
for ( int i = 0; i < ( int )(1e5); i++)
{
parent.Add(0);
}
dfs(parent, adj, 1);
for ( int i = 1; i <= n; i++) {
int node = i;
int cnt = 0;
while (parent[node] != -1) {
if (parent[node] < i)
cnt += 1;
node = parent[node];
}
Console.Write(cnt + " " );
}
}
static void Main() {
int N = 6;
List<List< int >> adj = new List<List< int >>();
for ( int i = 0; i < ( int )(1e5); i++)
{
adj.Add( new List< int >());
}
add_edge(adj, 1, 5);
add_edge(adj, 1, 4);
add_edge(adj, 4, 6);
add_edge(adj, 5, 3);
add_edge(adj, 5, 2);
countSmallerAncestors(adj, N);
}
}
|
Javascript
<script>
function add_edge(adj, u, v)
{
adj[u].push(v);
adj[v].push(u);
}
function dfs(parent, adj, u, par = -1)
{
parent[u] = par;
adj[u].forEach(child => {
if (child != par)
dfs(parent, adj, child, u);
});
}
function countSmallerAncestors(adj, n)
{
var parent = Array(100000).fill(0);
dfs(parent, adj, 1);
for ( var i = 1; i <= n; i++) {
var node = i;
var cnt = 0;
while (parent[node] != -1) {
if (parent[node] < i)
cnt += 1;
node = parent[node];
}
document.write( cnt + " " );
}
}
var N = 6;
var adj = Array.from(Array(100000), ()=>Array());
add_edge(adj, 1, 5);
add_edge(adj, 1, 4);
add_edge(adj, 4, 6);
add_edge(adj, 5, 3);
add_edge(adj, 5, 2);
countSmallerAncestors(adj, N);
</script>
|
Time Complexity: O(N2)
Auxiliary Space: O(N)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...