Count of exponential paths in a Binary Tree
Last Updated :
12 Jul, 2025
Given a Binary Tree, the task is to count the number of Exponential paths in the given Binary Tree.
Exponential Path is a path where root to leaf path contains all nodes being equal to xy, & where x is a minimum possible positive constant & y is a variable positive integer.
Example:
Input:
27
/ \
9 81
/ \ / \
3 10 70 243
/ \
81 909
Output: 2
Explanation:
There are 2 exponential path for
the above Binary Tree, for x = 3,
Path 1: 27 -> 9 -> 3
Path 2: 27 -> 81 -> 243 -> 81
Input:
8
/ \
4 81
/ \ / \
3 2 70 243
/ \
81 909
Output: 1
Approach: The idea is to use Preorder Tree Traversal. During preorder traversal of the given binary tree do the following:
- First find the value of x for which xy=root & x is minimum possible & y>0.
- If current value of the node is not equal to xy for some y>0, or pointer becomes NULL then return the count.
- If the current node is a leaf node then increment the count by 1.
- Recursively call for the left and right subtree with the updated count.
- After all recursive call, the value of count is number of exponential paths for a given binary tree.
Below is the implementation of the above approach:
C++
// C++ program to find the count
// exponential paths in Binary Tree
#include <bits/stdc++.h>
using namespace std;
// A Tree node
struct Node {
int key;
struct Node *left, *right;
};
// Function to create a new node
Node* newNode(int key)
{
Node* temp = new Node;
temp->key = key;
temp->left
= temp->right
= NULL;
return (temp);
}
// function to find x
int find_x(int n)
{
if (n == 1)
return 1;
double num, den, p;
// Take log10 of n
num = log10(n);
int x, no;
for (int i = 2; i <= n; i++) {
den = log10(i);
// Log(n) with base i
p = num / den;
// Raising i to the power p
no = (int)(pow(i, int(p)));
if (abs(no - n) < 1e-6) {
x = i;
break;
}
}
return x;
}
// function To check
// whether the given node
// equals to x^y for some y>0
bool is_key(int n, int x)
{
double p;
// Take logx(n) with base x
p = log10(n) / log10(x);
int no = (int)(pow(x, int(p)));
if (n == no)
return true;
return false;
}
// Utility function to count
// the exponent path
// in a given Binary tree
int evenPaths(struct Node* node,
int count, int x)
{
// Base Condition, when node pointer
// becomes null or node value is not
// a number of pow(x, y )
if (node == NULL
|| !is_key(node->key, x)) {
return count;
}
// Increment count when
// encounter leaf node
if (!node->left
&& !node->right) {
count++;
}
// Left recursive call
// save the value of count
count = evenPaths(
node->left, count, x);
// Right recursive call and
// return value of count
return evenPaths(
node->right, count, x);
}
// function to count exponential paths
int countExpPaths(
struct Node* node, int x)
{
return evenPaths(node, 0, x);
}
// Driver Code
int main()
{
// create Tree
Node* root = newNode(27);
root->left = newNode(9);
root->right = newNode(81);
root->left->left = newNode(3);
root->left->right = newNode(10);
root->right->left = newNode(70);
root->right->right = newNode(243);
root->right->right->left = newNode(81);
root->right->right->right = newNode(909);
// retrieve the value of x
int x = find_x(root->key);
// Function call
cout << countExpPaths(root, x);
return 0;
}
Java
// Java program to find the count
// exponential paths in Binary Tree
import java.util.*;
import java.lang.*;
class GFG{
// Structure of a Tree node
static class Node
{
int key;
Node left, right;
}
// Function to create a new node
static Node newNode(int key)
{
Node temp = new Node();
temp.key = key;
temp.left = temp.right = null;
return (temp);
}
// Function to find x
static int find_x(int n)
{
if (n == 1)
return 1;
double num, den, p;
// Take log10 of n
num = Math.log10(n);
int x = 0, no = 0;
for(int i = 2; i <= n; i++)
{
den = Math.log10(i);
// Log(n) with base i
p = num / den;
// Raising i to the power p
no = (int)(Math.pow(i, (int)p));
if (Math.abs(no - n) < 1e-6)
{
x = i;
break;
}
}
return x;
}
// Function to check whether the
// given node equals to x^y for some y>0
static boolean is_key(int n, int x)
{
double p;
// Take logx(n) with base x
p = Math.log10(n) / Math.log10(x);
int no = (int)(Math.pow(x, (int)p));
if (n == no)
return true;
return false;
}
// Utility function to count
// the exponent path in a
// given Binary tree
static int evenPaths(Node node, int count,
int x)
{
// Base Condition, when node pointer
// becomes null or node value is not
// a number of pow(x, y )
if (node == null || !is_key(node.key, x))
{
return count;
}
// Increment count when
// encounter leaf node
if (node.left == null &&
node.right == null)
{
count++;
}
// Left recursive call
// save the value of count
count = evenPaths(node.left,
count, x);
// Right recursive call and
// return value of count
return evenPaths(node.right,
count, x);
}
// Function to count exponential paths
static int countExpPaths(Node node, int x)
{
return evenPaths(node, 0, x);
}
// Driver code
public static void main(String[] args)
{
// Create Tree
Node root = newNode(27);
root.left = newNode(9);
root.right = newNode(81);
root.left.left = newNode(3);
root.left.right = newNode(10);
root.right.left = newNode(70);
root.right.right = newNode(243);
root.right.right.left = newNode(81);
root.right.right.right = newNode(909);
// Retrieve the value of x
int x = find_x(root.key);
// Function call
System.out.println(countExpPaths(root, x));
}
}
// This code is contributed by offbeat
Python3
# Python3 program to find the count
# exponential paths in Binary Tree
import math
# Structure of a Tree node
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
# Function to create a new node
def newNode(key):
temp = Node(key)
return temp
# Function to find x
def find_x(n):
if n == 1:
return 1
# Take log10 of n
num = math.log10(n)
x, no = 0, 0
for i in range(2, n + 1):
den = math.log10(i)
# Log(n) with base i
p = num / den
# Raising i to the power p
no = int(pow(i, int(p)))
if abs(no - n) < 1e-6:
x = i
break
return x
# Function to check whether the
# given node equals to x^y for some y>0
def is_key(n, x):
# Take logx(n) with base x
p = math.log10(n) / math.log10(x)
no = int(pow(x, int(p)))
if n == no:
return True
return False
# Utility function to count
# the exponent path in a
# given Binary tree
def evenPaths(node, count, x):
# Base Condition, when node pointer
# becomes null or node value is not
# a number of pow(x, y )
if node == None or not is_key(node.key, x):
return count
# Increment count when
# encounter leaf node
if node.left == None and node.right == None:
count+=1
# Left recursive call
# save the value of count
count = evenPaths(node.left, count, x)
# Right recursive call and
# return value of count
return evenPaths(node.right, count, x)
# Function to count exponential paths
def countExpPaths(node, x):
return evenPaths(node, 0, x)
# Create Tree
root = newNode(27)
root.left = newNode(9)
root.right = newNode(81)
root.left.left = newNode(3)
root.left.right = newNode(10)
root.right.left = newNode(70)
root.right.right = newNode(243)
root.right.right.left = newNode(81)
root.right.right.right = newNode(909)
# Retrieve the value of x
x = find_x(root.key)
# Function call
print(countExpPaths(root, x))
# This code is contributed by divyeshrabadiya07.
C#
// C# program to find the count
// exponential paths in Binary Tree
using System;
class GFG{
// Structure of a Tree node
public class Node
{
public int key;
public Node left, right;
}
// Function to create a new node
static Node newNode(int key)
{
Node temp = new Node();
temp.key = key;
temp.left = temp.right = null;
return (temp);
}
// Function to find x
static int find_x(int n)
{
if (n == 1)
return 1;
double num, den, p;
// Take log10 of n
num = Math.Log10(n);
int x = 0, no = 0;
for(int i = 2; i <= n; i++)
{
den = Math.Log10(i);
// Log(n) with base i
p = num / den;
// Raising i to the power p
no = (int)(Math.Pow(i, (int)p));
if (Math.Abs(no - n) < 0.000001)
{
x = i;
break;
}
}
return x;
}
// Function to check whether the
// given node equals to x^y for some y>0
static bool is_key(int n, int x)
{
double p;
// Take logx(n) with base x
p = Math.Log10(n) / Math.Log10(x);
int no = (int)(Math.Pow(x, (int)p));
if (n == no)
return true;
return false;
}
// Utility function to count
// the exponent path in a
// given Binary tree
static int evenPaths(Node node, int count,
int x)
{
// Base Condition, when node pointer
// becomes null or node value is not
// a number of pow(x, y )
if (node == null || !is_key(node.key, x))
{
return count;
}
// Increment count when
// encounter leaf node
if (node.left == null &&
node.right == null)
{
count++;
}
// Left recursive call
// save the value of count
count = evenPaths(node.left,
count, x);
// Right recursive call and
// return value of count
return evenPaths(node.right,
count, x);
}
// Function to count exponential paths
static int countExpPaths(Node node, int x)
{
return evenPaths(node, 0, x);
}
// Driver code
public static void Main(string[] args)
{
// Create Tree
Node root = newNode(27);
root.left = newNode(9);
root.right = newNode(81);
root.left.left = newNode(3);
root.left.right = newNode(10);
root.right.left = newNode(70);
root.right.right = newNode(243);
root.right.right.left = newNode(81);
root.right.right.right = newNode(909);
// Retrieve the value of x
int x = find_x(root.key);
// Function call
Console.Write(countExpPaths(root, x));
}
}
// This code is contributed by rutvik_56
JavaScript
<script>
// Javascript program to find the count
// exponential paths in Binary Tree
// Structure of a Tree node
class Node
{
constructor(key)
{
this.left = null;
this.right = null;
this.key = key;
}
}
// Function to create a new node
function newNode(key)
{
let temp = new Node(key);
return (temp);
}
// Function to find x
function find_x(n)
{
if (n == 1)
return 1;
let num, den, p;
// Take log10 of n
num = Math.log10(n);
let x = 0, no = 0;
for(let i = 2; i <= n; i++)
{
den = Math.log10(i);
// Log(n) with base i
p = num / den;
// Raising i to the power p
no = parseInt(Math.pow(
i, parseInt(p, 10)), 10);
if (Math.abs(no - n) < 1e-6)
{
x = i;
break;
}
}
return x;
}
// Function to check whether the
// given node equals to x^y for some y>0
function is_key(n, x)
{
let p;
// Take logx(n) with base x
p = Math.log10(n) / Math.log10(x);
let no = parseInt(Math.pow(
x, parseInt(p, 10)), 10);
if (n == no)
return true;
return false;
}
// Utility function to count
// the exponent path in a
// given Binary tree
function evenPaths(node, count, x)
{
// Base Condition, when node pointer
// becomes null or node value is not
// a number of pow(x, y )
if (node == null || !is_key(node.key, x))
{
return count;
}
// Increment count when
// encounter leaf node
if (node.left == null &&
node.right == null)
{
count++;
}
// Left recursive call
// save the value of count
count = evenPaths(node.left,
count, x);
// Right recursive call and
// return value of count
return evenPaths(node.right,
count, x);
}
// Function to count exponential paths
function countExpPaths(node, x)
{
return evenPaths(node, 0, x);
}
// Driver code
// Create Tree
let root = newNode(27);
root.left = newNode(9);
root.right = newNode(81);
root.left.left = newNode(3);
root.left.right = newNode(10);
root.right.left = newNode(70);
root.right.right = newNode(243);
root.right.right.left = newNode(81);
root.right.right.right = newNode(909);
// Retrieve the value of x
let x = find_x(root.key);
// Function call
document.write(countExpPaths(root, x));
// This code is contributed by mukesh07
</script>
Time Complexity: O(n log n) as it contains a loop that runs from 2 to n, and for each i, it calculates log10(i) and performs a division and a power operation. The time complexity of the function is_key is O(log n) as it calculates log10(n) / log10(x) and performs a power operation. The time complexity of the function evenPaths is O(n) as it traverses each node in the binary tree once
Auxiliary Space: O(h), where h is the height of the binary tree. This is because the recursive functions evenPaths and countExpPaths use the call stack to store the function call frames, and the maximum number of function calls on the call stack is equal to the height of the binary tree. Additionally, the program uses O(1) extra space to store variables and O(n) space to store the binary tree.
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