Count of nodes that are greater than Ancestors
Last Updated :
12 Jul, 2025
Given the root of a tree, the task is to find the count of nodes which are greater than all of its ancestors.
Examples:
Input:
4
/ \
5 2
/ \
3 6
Output: 3
The nodes are 4, 5 and 6.
Input:
10
/ \
8 6
\ \
3 5
/
1
Output: 1
Approach: The problem can be solved using dfs. In every function call, pass a variable maxx which stores the maximum among all the nodes traversed so far, and every node whose value is greater than maxx is the node that satisfies the given condition. Hence, increment the count.
Below is the implementation of the above approach:
C++
// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
// Structure for the node of the tree
struct Tree {
int val;
Tree* left;
Tree* right;
Tree(int _val)
{
val = _val;
left = NULL;
right = NULL;
}
};
// Dfs Function
void dfs(Tree* node, int maxx, int& count)
{
// Base case
if (node == NULL) {
return;
}
else {
// Increment the count if the current
// node's value is greater than the
// maximum value in it's ancestors
if (node->val > maxx)
count++;
// Left traversal
dfs(node->left, max(maxx, node->val), count);
// Right traversal
dfs(node->right, max(maxx, node->val), count);
}
}
// Driver code
int main()
{
Tree* root = new Tree(4);
root->left = new Tree(5);
root->right = new Tree(2);
root->right->left = new Tree(3);
root->right->right = new Tree(6);
// To store the required count
int count = 0;
dfs(root, INT_MIN, count);
cout << count;
return 0;
}
Java
// Java implementation of the approach
class GFG
{
static int count;
// Structure for the node of the tree
static class Tree
{
int val;
Tree left;
Tree right;
Tree(int _val)
{
val = _val;
left = null;
right = null;
}
};
// Dfs Function
static void dfs(Tree node, int maxx)
{
// Base case
if (node == null)
{
return;
}
else
{
// Increment the count if the current
// node's value is greater than the
// maximum value in it's ancestors
if (node.val > maxx)
count++;
// Left traversal
dfs(node.left, Math.max(maxx, node.val));
// Right traversal
dfs(node.right, Math.max(maxx, node.val));
}
}
// Driver code
public static void main(String[] args)
{
Tree root = new Tree(4);
root.left = new Tree(5);
root.right = new Tree(2);
root.right.left = new Tree(3);
root.right.right = new Tree(6);
// To store the required count
count = 0;
dfs(root, Integer.MIN_VALUE);
System.out.print(count);
}
}
// This code is contributed by 29AjayKumar
Python
# Python3 program for the
# above approach
from collections import deque
# A Tree node
class Tree:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
count = 0
# Dfs Function
def dfs(node, maxx):
global count
# Base case
if (node == None):
return
else:
# Increment the count if
# the current node's value
# is greater than the maximum
# value in it's ancestors
if (node.val > maxx):
count += 1
# Left traversal
dfs(node.left,
max(maxx,
node.val))
# Right traversal
dfs(node.right,
max(maxx,
node.val))
# Driver code
if __name__ == '__main__':
root = Tree(4)
root.left = Tree(5)
root.right = Tree(2)
root.right.left = Tree(3)
root.right.right = Tree(6)
# To store the required
# count
count = 0
dfs(root,
-10 ** 9)
print(count)
# This code is contributed by Mohit Kumar 29
C#
// C# implementation of the approach
using System;
class GFG
{
static int count;
// Structure for the node of the tree
public class Tree
{
public int val;
public Tree left;
public Tree right;
public Tree(int _val)
{
val = _val;
left = null;
right = null;
}
};
// Dfs Function
static void dfs(Tree node, int maxx)
{
// Base case
if (node == null)
{
return;
}
else
{
// Increment the count if the current
// node's value is greater than the
// maximum value in it's ancestors
if (node.val > maxx)
count++;
// Left traversal
dfs(node.left, Math.Max(maxx, node.val));
// Right traversal
dfs(node.right, Math.Max(maxx, node.val));
}
}
// Driver code
public static void Main(String[] args)
{
Tree root = new Tree(4);
root.left = new Tree(5);
root.right = new Tree(2);
root.right.left = new Tree(3);
root.right.right = new Tree(6);
// To store the required count
count = 0;
dfs(root, int.MinValue);
Console.Write(count);
}
}
// This code is contributed by Rajput-Ji
Javascript
<script>
// Javascript implementation of the approach
let count=0;
// Structure for the node of the tree
class Tree
{
constructor(val)
{
this.val=val;
this.left=this.right=null;
}
}
// Dfs Function
function dfs(node,maxx)
{
// Base case
if (node == null)
{
return;
}
else
{
// Increment the count if the current
// node's value is greater than the
// maximum value in it's ancestors
if (node.val > maxx)
count++;
// Left traversal
dfs(node.left, Math.max(maxx, node.val));
// Right traversal
dfs(node.right, Math.max(maxx, node.val));
}
}
// Driver code
let root = new Tree(4);
root.left = new Tree(5);
root.right = new Tree(2);
root.right.left = new Tree(3);
root.right.right = new Tree(6);
// To store the required count
count = 0;
dfs(root, Number.MIN_VALUE);
document.write(count);
// This code is contributed by unknown2108
</script>
Time Complexity: O(N) where N is the number of nodes in given binary tree.
Space Complexity: O(h) where h is the height of binary tree due to stack recursion call.
Approach: Breadth-First Search (BFS) with Tracking Maximum Ancestor Value
This method employs a breadth-first search (BFS) strategy to explore nodes one level at a time, simultaneously recording the
highest value encountered from the root to each node with a queue. For every node, we verify if its value surpasses this
recorded maximum.
Follow the below steps:
- Intitalize the counter to zero.
- Apply a queue for BFS, with each item in the queue being a tuple that includes a node and the highest value found on the path leading to that node.
- For every node, check if its value is greater than the existing highest value.
- If the node’s value is greater, increment the counter.
- Update the current maximum value to be the maximum of the current node’s value and the current maximum value.
- Add the left and right children of the current node to the queue along with the updated maximum value.
- Return the counter after the traversal is complete.
Below is the implementation of the above approach:
Python
from collections import deque
# Definition for a binary tree node.
class TreeNode:
def __init__(self, value=0, left=None, right=None):
self.value = value
self.left = left
self.right = right
# Function to count nodes greater than all of their ancestors using BFS
def count_greater_nodes_bfs(root):
if not root:
return 0 # If the tree is empty, return 0
count = 0 # Initialize the counter for nodes greater than all ancestors
queue = deque([(root, float('-inf'))]) # Initialize the queue with the root node and negative infinity as max value
# Perform BFS
while queue:
node, max_value = queue.popleft() # Get the next node and the max value encountered so far
# Check if the current node's value is greater than the max value encountered so far
if node.value >= max_value:
count += 1 # Increment the counter if the condition is satisfied
# Update the max value encountered so far
new_max_value = max(max_value, node.value)
# Add the left child to the queue if it exists
if node.left:
queue.append((node.left, new_max_value))
# Add the right child to the queue if it exists
if node.right:
queue.append((node.right, new_max_value))
return count # Return the final count
# Define the example trees
# Tree 1:
# 4
# / \
# 5 2
# / \
# 3 6
root1 = TreeNode(4, TreeNode(5), TreeNode(2, TreeNode(3), TreeNode(6)))
# Tree 2:
# 10
# / \
# 8 6
# \ \
# 3 5
# /
# 1
root2 = TreeNode(10, TreeNode(8, right=TreeNode(3, left=TreeNode(1))), TreeNode(6, right=TreeNode(5)))
# Test the function with the example trees
print(count_greater_nodes_bfs(root1))
print(count_greater_nodes_bfs(root2))
Time Complexity: O(n) where n is the number of nodes in the tree.
Space Complexity: O(n)
Similar Reads
Count ancestors with smaller value for each node of a Binary Tree 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 2Output: 0 1 1 1 1 2Explanation: Since node
9 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
15+ min read
Count of ancestors with smaller value for each node of an N-ary Tree Given an N-ary tree consisting of N nodes with values from 1 to N rooted at 1, for all nodes, print the number of ancestors having a smaller value than the current node. Example: Input: Below is the given Tree: 1 / \ 4 5 / / | \ 6 3 2 7 Output: 0 1 1 1 1 2 2 Explanation: Since node 1 is the root nod
9 min read
Count BST nodes that lie in a given range Given a Binary Search Tree (BST) and a range [l, h], the task is to count the number of nodes in the BST that lie in the given range.Examples: Input: Output: 3Explanation: There are three nodes in range [5, 45] = 5, 10 and 40.Input: Output: 4Explanation: There are four nodes in range [10, 100] = 10,
14 min read
Number of nodes greater than a given value in n-ary tree Given a n-ary tree and a number x, find and return the number of nodes which are greater than x. Example: In the given tree, x = 7 Number of nodes greater than x are 4. Approach: The idea is maintain a count variable initialize to 0. Traverse the tree and compare root data with x. If root data is gr
6 min read
Count the number of common ancestors of given K nodes in a N-ary Tree Given an N-ary tree root and a list of K nodes, the task is to find the number of common ancestors of the given K nodes in the tree. Example: Input: root = 3 / \ 2 1 / \ / | \ 9 7 8 6 3K = {7, 2, 9}Output: 2 Explanation: The common ancestors of the nodes 7, 9 and 2 are 2 and 3 Input: root = 2 \ 1 \
10 min read