Count of strictly increasing and decreasing paths in directed Binary Tree
Last Updated :
23 Jul, 2025
Given a directed binary tree of N nodes whose edges are directed from the parent to the child, the task is to count the number of strictly increasing and decreasing paths.
Note: A path starts at the root and ends at any leaf.
Examples:
Input: N = 6
tree = 6
/ \
4 7
\ / \
5 6 8
Output: 10 8
Explanation: For the above binary tree, the strictly increasing paths are :
All the paths consisting of a single node are = 6.
The paths containing two nodes are: 4->5, 7->8, 6->7 = 3.
The paths containing three nodes are: 6->7->8 = 1.
Hence, the count of strictly increasing paths is 6 + 3 + 1 = 10.
For the above binary tree, the strictly decreasing paths are:
All the paths consisting of a single node are = 6.
The paths containing two nodes are: 6->4, 7->6 = 2.
Hence, the count of strictly decreasing paths is 6 + 2 = 8.
Input: N = 5
tree 15
/
8
\
2
/ \
13 9
Output: 7 8
Explanation:
For the above binary tree, the strictly increasing paths are:
All the paths consisting of a single node are = 5.
The paths containing two nodes are: 2->9, 2->13 = 2.
Hence, the count of strictly increasing paths is 5 + 2 = 7.
For the above binary tree, the strictly decreasing paths are:
All the paths consisting of a single node are = 5.
The paths containing two nodes are:15->8, 8->2 = 2.
The paths containing three nodes are: 15->8->2 = 1.
Hence, the count of strictly decreasing paths is 5 + 2 + 1 = 8.
Approach: The problem can be solved based on the following observation:
If a path starting from any node u is strictly increasing and its value is greater than the value of its parent (say v), then all the strictly increasing paths starting from u are also strictly increasing paths when the starting node is v. The same is true in case of strictly decreasing paths.
From the above observation, the problem can be solved with the help of recursion. Follow the steps below to solve the problem:
- Use a recursive function to traverse the tree starting from the root and for each node return the count of strictly increasing and strictly decreasing paths from that node.
- In each recursion:
- Check if the path from the current node to a child (left or right) is increasing or decreasing.
- Call the recursive function for the child.
- Add the count of increasing or decreasing paths to the total count if the path from the current node to the child is increasing or decreasing respectively.
- Return the final count of increasing or decreasing path obtained for root.
Below is the implementation of the above approach :
C++
// C++ code to implement the approach
#include <bits/stdc++.h>
using namespace std;
// Following is the TreeNode
// class structure:
template <typename T>
class TreeNode {
public:
T data;
TreeNode<T>* left;
TreeNode<T>* right;
TreeNode(T data)
{
this->data = data;
left = NULL;
right = NULL;
}
};
// Helper function to get the answer
pair<int, int> countPathsHelper(TreeNode<int>* root,
int& increase,
int& decrease)
{
// If the root is NULL,
// then no strictly increasing or
// decreasing path.
if (root == NULL) {
return { 0, 0 };
}
// Call the function for both
// the left and right child.
pair<int, int> p1
= countPathsHelper(root->left,
increase, decrease);
pair<int, int> p2
= countPathsHelper(root->right,
increase, decrease);
// Initialize 'inc' and 'dec' to 1
int inc = 1, dec = 1;
// If the left child is not NULL.
if (root->left != NULL) {
// Check if the value is
// increasing from parent to child.
if (root->data < root->left->data) {
// Add the count of strictly
// increasing paths of
// child to parent.
inc += p1.first;
}
// Check if the value is decreasing
// from parent to child.
if (root->data > root->left->data) {
// Add the count of strictly
// decreasing paths of
// child to parent.
dec += p1.second;
}
}
if (root->right != NULL) {
// Check if the value is
// increasing from parent to child.
if (root->data < root->right->data) {
// Add the count of strictly
// increasing paths of
// child to parent.
inc += p2.first;
}
// Check if the value is
// decreasing from parent to child
if (root->data > root->right->data) {
// Add the count of strictly
// decreasing paths of
// child to parent.
dec += p2.second;
}
}
// Add the total count of
// strictly increasing paths to
// the global strictly increasing
// paths counter.
increase += inc;
// Add the total count of
// strictly decreasing paths to
// the global strictly
// decreasing paths counter.
decrease += dec;
return { inc, dec };
}
// Function to count the paths
pair<int, int> countPaths(TreeNode<int>* root)
{
// 'increase' stores the
// total strictly increasing paths.
int increase = 0;
// 'decrease' stores the
// total strictly decreasing paths.
int decrease = 0;
countPathsHelper(root, increase, decrease);
return { increase, decrease };
}
// Driver code
int main()
{
int N = 6;
TreeNode<int>* root
= new TreeNode<int>(N);
root->left = new TreeNode<int>(4);
root->right = new TreeNode<int>(7);
root->left->right = new TreeNode<int>(5);
root->right->left = new TreeNode<int>(6);
root->right->right = new TreeNode<int>(8);
// Function call
pair<int, int> ans = countPaths(root);
cout << ans.first << " " << ans.second;
return 0;
}
Java
// Java code for the above approach:
import java.util.*;
public class Main {
static class Node {
int data;
Node left;
Node right;
Node(int data_value)
{
data = data_value;
this.left = null;
this.right = null;
}
}
// 'increase' stores the
// total strictly increasing paths.
static int increase;
// 'decrease' stores the
// total strictly decreasing paths.
static int decrease;
// Helper function to get the answer
static int[] countPathsHelper(Node root)
{
// If the root is NULL,
// then no strictly increasing or
// decreasing path.
if (root == null) {
int[] zero = {0,0};
return zero;
}
// Call the function for both
// the left and right child.
int[] p1
= countPathsHelper(root.left);
int[] p2
= countPathsHelper(root.right);
// Initialize 'inc' and 'dec' to 1
int inc = 1, dec = 1;
// If the left child is not NULL.
if (root.left != null) {
// Check if the value is
// increasing from parent to child.
if (root.data < root.left.data) {
// Add the count of strictly
// increasing paths of
// child to parent.
inc += p1[0];
}
// Check if the value is decreasing
// from parent to child.
if (root.data > root.left.data) {
// Add the count of strictly
// decreasing paths of
// child to parent.
dec += p1[1];
}
}
if (root.right != null) {
// Check if the value is
// increasing from parent to child.
if (root.data < root.right.data) {
// Add the count of strictly
// increasing paths of
// child to parent.
inc += p2[0];
}
// Check if the value is
// decreasing from parent to child
if (root.data > root.right.data) {
// Add the count of strictly
// decreasing paths of
// child to parent.
dec += p2[1];
}
}
// Add the total count of
// strictly increasing paths to
// the global strictly increasing
// paths counter.
increase += inc;
// Add the total count of
// strictly decreasing paths to
// the global strictly
// decreasing paths counter.
decrease += dec;
int[] ans = {inc,dec};
return ans;
}
// Function to count the paths
static int[] countPaths(Node root)
{
increase=0;
decrease=0;
countPathsHelper(root);
int[] ans = {increase,decrease};
return ans;
}
public static void main(String args[]) {
int N = 6;
Node root = new Node(N);
root.left = new Node(4);
root.right = new Node(7);
root.left.right = new Node(5);
root.right.left = new Node(6);
root.right.right = new Node(8);
// Function call
int[] ans = countPaths(root);
System.out.println(ans[0] + " " + ans[1]);
}
}
// This code has been contributed by Sachin Sahara (sachin801)
Python3
# Python code for the above approach
## structure for a node
class Node:
def __init__(self, d):
self.data = d
self.left = None
self.right = None
## 'increase' stores the
## total strictly increasing paths.
increase = 0
## 'decrease' stores the
## total strictly decreasing paths.
decrease = 0
## Helper function to get the answer
def countPathsHelper(root):
global increase
global decrease
## If the root is NULL,
## then no strictly increasing or
## decreasing path.
if (root == None):
zero = [0, 0]
return zero
## Call the function for both
## the left and right child.
p1 = countPathsHelper(root.left)
p2 = countPathsHelper(root.right)
## Initialize 'inc' and 'dec' to 1
inc = 1
dec = 1
## If the left child is not NULL.
if (root.left != None):
## Check if the value is
## increasing from parent to child.
if (root.data < root.left.data):
## Add the count of strictly
## increasing paths of
## child to parent.
inc += p1[0];
## Check if the value is decreasing
## from parent to child.
if (root.data > root.left.data):
## Add the count of strictly
## decreasing paths of
## child to parent.
dec += p1[1]
if (root.right != None):
## Check if the value is
## increasing from parent to child.
if (root.data < root.right.data):
## Add the count of strictly
## increasing paths of
## child to parent.
inc += p2[0]
## Check if the value is
## decreasing from parent to child
if (root.data > root.right.data):
## Add the count of strictly
## decreasing paths of
## child to parent.
dec += p2[1]
## Add the total count of
## strictly increasing paths to
## the global strictly increasing
## paths counter.
increase += inc
## Add the total count of
## strictly decreasing paths to
## the global strictly
## decreasing paths counter.
decrease += dec
ans = [inc, dec]
return ans
## Function to count the paths
def countPaths(root):
global increase
global decrease
increase = 0
decrease = 0
countPathsHelper(root)
ans = [increase, decrease]
return ans
# Driver Code
if __name__=='__main__':
N = 6
root = Node(N)
root.left = Node(4)
root.right = Node(7)
root.left.right = Node(5)
root.right.left = Node(6)
root.right.right = Node(8)
## Function call
ans = countPaths(root)
print(ans[0], ans[1])
# This code is contributed by entertain2022.
C#
// C# program to count the number of
// strictly increasing and decreasing paths
using System;
public class GFG{
public class Node {
public int data;
public Node left;
public Node right;
public Node(int data_value)
{
data = data_value;
this.left = null;
this.right = null;
}
}
// 'increase' stores the
// total strictly increasing paths.
static int increase;
// 'decrease' stores the
// total strictly decreasing paths.
static int decrease;
// Helper function to get the answer
static int[] countPathsHelper(Node root)
{
// If the root is NULL,
// then no strictly increasing or
// decreasing path.
if (root == null) {
int[] zero = {0,0};
return zero;
}
// Call the function for both
// the left and right child.
int[] p1 = countPathsHelper(root.left);
int[] p2 = countPathsHelper(root.right);
// Initialize 'inc' and 'dec' to 1
int inc = 1, dec = 1;
// If the left child is not NULL.
if (root.left != null) {
// Check if the value is
// increasing from parent to child.
if (root.data < root.left.data) {
// Add the count of strictly
// increasing paths of
// child to parent.
inc += p1[0];
}
// Check if the value is decreasing
// from parent to child.
if (root.data > root.left.data) {
// Add the count of strictly
// decreasing paths of
// child to parent.
dec += p1[1];
}
}
if (root.right != null) {
// Check if the value is
// increasing from parent to child.
if (root.data < root.right.data) {
// Add the count of strictly
// increasing paths of
// child to parent.
inc += p2[0];
}
// Check if the value is
// decreasing from parent to child
if (root.data > root.right.data) {
// Add the count of strictly
// decreasing paths of
// child to parent.
dec += p2[1];
}
}
// Add the total count of
// strictly increasing paths to
// the global strictly increasing
// paths counter.
increase += inc;
// Add the total count of
// strictly decreasing paths to
// the global strictly
// decreasing paths counter.
decrease += dec;
int[] ans = {inc,dec};
return ans;
}
// Function to count the paths
static int[] countPaths(Node root)
{
increase=0;
decrease=0;
countPathsHelper(root);
int[] ans = {increase,decrease};
return ans;
}
static public void Main (){
//Code
int N = 6;
Node root = new Node(N);
root.left = new Node(4);
root.right = new Node(7);
root.left.right = new Node(5);
root.right.left = new Node(6);
root.right.right = new Node(8);
// Function call
int[] ans = countPaths(root);
Console.Write(ans[0] + " " + ans[1]);
}
}
// This code is contributed by shruti456rawal
JavaScript
// JavaScript code for the above approach
class TreeNode {
constructor(data) {
this.data = data;
this.left = null;
this.right = null;
}
}
function countPathsHelper(root, increase, decrease) {
if (root === null) {
return { inc: 0, dec: 0 };
}
const p1 = countPathsHelper(root.left, increase, decrease);
const p2 = countPathsHelper(root.right, increase, decrease);
let inc = 1;
let dec = 1;
if (root.left !== null) {
if (root.data < root.left.data) {
inc += p1.inc;
}
if (root.data > root.left.data) {
dec += p1.dec;
}
}
if (root.right !== null) {
if (root.data < root.right.data) {
inc += p2.inc;
}
if (root.data > root.right.data) {
dec += p2.dec;
}
}
increase.val += inc;
decrease.val += dec;
return { inc, dec };
}
function countPaths(root) {
const increase = { val: 0 };
const decrease = { val: 0 };
countPathsHelper(root, increase, decrease);
return { increase: increase.val, decrease: decrease.val };
}
const root = new TreeNode(6);
root.left = new TreeNode(4);
root.right = new TreeNode(7);
root.left.right = new TreeNode(5);
root.right.left = new TreeNode(6);
root.right.right = new TreeNode(8);
console.log(countPaths(root)['increase'] + " " + countPaths(root)['decrease']);
// This code is contributed by Potta Lokesh
Time Complexity: O(N)
Auxiliary Space: O(N)
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem