Given a Binary Tree consisting of N nodes, the task is to find the number of paths from the root to any node X, such that all the node values in that path are at most X.
Examples:
Input: Below is the given Tree:

Output: 4
Explanation:

The paths from the root to any node X that have value at most values of node X are:
- Node 3(root node): It always follows the given property.
- Node 4: The path starting from the root to node with value 4 has order (3 ? 4), with the maximum value of a node being 4.
- Node 5: The path starting from the root to node with value 5 has order (3 ? 4 ? 5), with the maximum value of a node being 5.
- Node 3: The path starting from the root to node with value 3 has order (3 ? 1 ? 3), with the maximum value of a node being 3.
Therefore, the count of required paths is 4.
Input: Below is the given Tree:

Output: 3
Approach – using DFS: The idea is to traverse the tree using a Depth First Search traversal while checking if the maximum value from root to any node X is equal to X or not.
Follow the steps below to solve the problem:
- Initialize a variable, say count as 0 to store the count of paths from the root to any node X having all the node values in that path is at most X.
- Traverse the tree recursively using depth-first-search and perform the following steps:
- Every recursive call for DFS Traversal, apart from the parent node, pass the maximum value of the node obtained so far in that path.
- Check if the current node value is greater or equal to the maximum value obtained so far, then increment the value of count by 1 and update the maximum value to the current node value.
- After completing the above steps, print the value of count as the result.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int val;
Node *left, *right;
};
struct Node* newNode( int data)
{
struct Node* temp = new Node();
temp->val = data;
temp->left = NULL;
temp->right = NULL;
return temp;
}
int countNodes(Node* root, int max)
{
if (!root)
return 0;
if (root->val >= max)
return 1 + countNodes(root->left,
root->val)
+ countNodes(root->right, root->val);
return countNodes(root->left,
max)
+ countNodes(root->right,
max);
}
int main()
{
Node* root = NULL;
root = newNode(3);
root->left = newNode(1);
root->right = newNode(4);
root->left->left = newNode(3);
root->right->left = newNode(1);
root->right->right = newNode(5);
cout << countNodes(root, INT_MIN);
return 0;
}
|
Java
import java.util.*;
class Node {
int data;
Node left, right;
public Node( int item)
{
data = item;
left = right = null ;
}
}
class GFG {
Node root;
public GFG()
{
root = null ;
}
static int countNodes(Node root, int max)
{
if (root == null )
return 0 ;
if (root.data >= max)
return 1 + countNodes(root.left,
root.data)
+ countNodes(root.right, root.data);
return countNodes(root.left,
max)
+ countNodes(root.right,
max);
}
public static void main (String[] args)
{
GFG tree = new GFG();
tree.root = new Node( 3 );
tree.root.left = new Node( 1 );
tree.root.right = new Node( 4 );
tree.root.left.left = new Node( 3 );
tree.root.right.left = new Node( 1 );
tree.root.right.right = new Node( 5 );
System.out.println(countNodes(tree.root, Integer.MIN_VALUE));
}
}
|
Python3
class Node:
def __init__( self , x):
self .val = x
self .left = None
self .right = None
def countNodes(root, max ):
if ( not root):
return 0
if (root.val > = max ):
return 1 + countNodes(root.left,root.val) + countNodes(root.right, root.val)
return countNodes(root.left, max ) + countNodes(root.right, max )
if __name__ = = '__main__' :
root = Node( 3 )
root.left = Node( 1 )
root.right = Node( 4 )
root.left.left = Node( 3 )
root.right.left = Node( 1 )
root.right.right = Node( 5 )
print (countNodes(root, - 10 * * 19 ))
|
C#
using System;
class Node {
public int data;
public Node left, right;
public Node( int item)
{
data = item;
left = right = null ;
}
}
public class GFG
{
Node root;
public GFG()
{
root = null ;
}
static int countNodes(Node root, int max)
{
if (root == null )
return 0;
if (root.data >= max)
return 1 + countNodes(root.left,
root.data)
+ countNodes(root.right, root.data);
return countNodes(root.left,
max)
+ countNodes(root.right,
max);
}
public static void Main(String []args)
{
GFG tree = new GFG();
tree.root = new Node(3);
tree.root.left = new Node(1);
tree.root.right = new Node(4);
tree.root.left.left = new Node(3);
tree.root.right.left = new Node(1);
tree.root.right.right = new Node(5);
Console.WriteLine(countNodes(tree.root, Int32.MinValue));
}
}
|
Javascript
<script>
class Node
{
constructor(item) {
this .left = null ;
this .right = null ;
this .data = item;
}
}
let root;
class GFG
{
constructor() {
root = null ;
}
}
function countNodes(root, max)
{
if (root == null )
return 0;
if (root.data >= max)
return 1 + countNodes(root.left, root.data)
+ countNodes(root.right, root.data);
return countNodes(root.left, max)
+ countNodes(root.right, max);
}
let tree = new GFG();
tree.root = new Node(3);
tree.root.left = new Node(1);
tree.root.right = new Node(4);
tree.root.left.left = new Node(3);
tree.root.right.left = new Node(1);
tree.root.right.right = new Node(5);
document.write(countNodes(tree.root, Number.MIN_VALUE));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N)
Approach using BFS: The idea is to traverse the tree using breadth-first search while checking if the maximum value from root to X is equal to X. Follow the steps below to solve the problem:
- Initialize a variable, say count as 0 to store the count of paths from the root to any node X having all the node values in that path is at most X and a queue Q of pairs to perform the BFS Traversal.
- Push the root node with INT_MIN as the maximum value in the queue.
- Now, until Q is non-empty perform the following:
- Pop the front node from the queue.
- If the front node value is at least the current maximum value obtained so far, then increment the value of count by 1.
- Update the maximum value that occurred so far with the current node value.
- If the left and right nodes exist for the current popped node then push it into the queue Q with the updated maximum value in the above step.
- After completing the above steps, print the value of count as the result.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
int val;
Node *left, *right;
};
struct Node* newNode( int data)
{
struct Node* temp = new Node();
temp->val = data;
temp->left = NULL;
temp->right = NULL;
return temp;
}
int countNodes(Node* root)
{
queue<pair<Node*, int > > q;
int m = INT_MIN;
q.push({ root, m });
int count = 0;
while (!q.empty()) {
auto temp = q.front();
q.pop();
Node* node = temp.first;
int num = temp.second;
if (node->val >= num)
count++;
m = max(node->val, num);
if (node->left)
q.push({ node->left, m });
if (node->right)
q.push({ node->right, m });
}
return count;
}
int main()
{
Node* root = NULL;
root = newNode(3);
root->left = newNode(1);
root->right = newNode(4);
root->left->left = newNode(3);
root->right->left = newNode(1);
root->right->right = newNode(5);
cout << countNodes(root);
return 0;
}
|
Java
import java.util.*;
class Node {
int val;
Node left, right;
public Node( int data)
{
val = data;
left = right = null ;
}
}
class Pair {
Node x;
int y;
public Pair(Node x, int y)
{
this .x = x;
this .y = y;
}
}
public class Main
{
static Node newNode( int data)
{
Node temp = new Node(data);
return temp;
}
static int countNodes(Node root)
{
Vector<Pair> q = new Vector<Pair>();
int m = Integer.MIN_VALUE;
q.add( new Pair(root, m));
int count = 0 ;
while (q.size() > 0 ) {
Pair temp = q.get( 0 );
q.remove( 0 );
Node node = temp.x;
int num = temp.y;
if (node.val >= num)
count++;
m = Math.max(node.val, num);
if (node.left != null )
q.add( new Pair(node.left, m));
if (node.right != null )
q.add( new Pair(node.right, m));
}
return count;
}
public static void main(String[] args) {
Node root = null ;
root = newNode( 3 );
root.left = newNode( 1 );
root.right = newNode( 4 );
root.left.left = newNode( 3 );
root.right.left = newNode( 1 );
root.right.right = newNode( 5 );
System.out.println(countNodes(root));
}
}
|
Python3
import sys
class Node:
def __init__( self , data):
self .val = data
self .left = None
self .right = None
def newNode(data):
temp = Node(data)
return temp
def countNodes(root):
q = []
m = - sys.maxsize
q.append([ root, m ])
count = 0
while ( len (q) > 0 ):
temp = q[ 0 ]
q.pop( 0 )
node = temp[ 0 ]
num = temp[ 1 ]
if (node.val > = num):
count + = 1
m = max (node.val, num)
if (node.left ! = None ):
q.append([ node.left, m ])
if (node.right ! = None ):
q.append([ node.right, m ])
return count
root = None
root = newNode( 3 )
root.left = newNode( 1 )
root.right = newNode( 4 )
root.left.left = newNode( 3 )
root.right.left = newNode( 1 )
root.right.right = newNode( 5 )
print (countNodes(root))
|
C#
using System;
using System.Collections;
class GFG {
class Node {
public int val;
public Node left, right;
public Node( int data)
{
val = data;
left = right = null ;
}
}
static Node newNode( int data)
{
Node temp = new Node(data);
return temp;
}
static int countNodes(Node root)
{
Queue q = new Queue();
int m = Int32.MinValue;
q.Enqueue( new Tuple<Node, int >(root, m));
int count = 0;
while (q.Count > 0) {
Tuple<Node, int > temp = (Tuple<Node, int >)q.Peek();
q.Dequeue();
Node node = temp.Item1;
int num = temp.Item2;
if (node.val >= num)
count++;
m = Math.Max(node.val, num);
if (node.left != null )
q.Enqueue( new Tuple<Node, int >(node.left, m));
if (node.right != null )
q.Enqueue( new Tuple<Node, int >(node.right, m));
}
return count;
}
static void Main()
{
Node root = null ;
root = newNode(3);
root.left = newNode(1);
root.right = newNode(4);
root.left.left = newNode(3);
root.right.left = newNode(1);
root.right.right = newNode(5);
Console.Write(countNodes(root));
}
}
|
Javascript
<script>
class Node
{
constructor(data) {
this .left = null ;
this .right = null ;
this .val = data;
}
}
function newNode(data)
{
let temp = new Node(data);
return temp;
}
function countNodes(root)
{
let q = [];
let m = Number.MIN_VALUE;
q.push([ root, m ]);
let count = 0;
while (q.length > 0) {
let temp = q[0];
q.shift();
let node = temp[0];
let num = temp[1];
if (node.val >= num)
count++;
m = Math.max(node.val, num);
if (node.left)
q.push([ node.left, m ]);
if (node.right)
q.push([ node.right, m ]);
}
return count;
}
let root = null ;
root = newNode(3);
root.left = newNode(1);
root.right = newNode(4);
root.left.left = newNode(3);
root.right.left = newNode(1);
root.right.right = newNode(5);
document.write(countNodes(root));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N)