# 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:

## Javascript



Output:

0 1 1 1 1 2

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

My Personal Notes arrow_drop_up