Check whether nodes of Binary Tree form Arithmetic, Geometric or Harmonic Progression
Last Updated :
12 Jul, 2025
Given a binary tree, the task is to check whether the nodes in this tree form an arithmetic progression, geometric progression or harmonic progression.
Examples:
Input:
4
/ \
2 16
/ \ / \
1 8 64 32
Output: Geometric Progression
Explanation:
The nodes of the binary tree can be used
to form a Geometric Progression as follows -
{1, 2, 4, 8, 16, 32, 64}
Input:
15
/ \
5 10
/ \ \
25 35 20
Output: Arithmetic Progression
Explanation:
The nodes of the binary tree can be used
to form a Arithmetic Progression as follows -
{5, 10, 15, 20, 25, 35}
Approach: The idea is to traverse the Binary Tree using Level-order Traversal and store all the nodes in an array and then check that the array can be used to form an arithmetic, geometric or harmonic progression.
- To check a sequence is in arithmetic progression or not, sort the sequence and check that the common difference between consecutive elements of the array is the same.
- To check a sequence is in geometric progression or not, sort the sequence and check that the common ratio between the consecutive elements of the array is the same.
- To check a sequence is in harmonic progression or not, find the reciprocal of every element and then sort the array and check that the common difference between the consecutive elements is the same.
Below is the implementation of the above approach:
C++
// C++ implementation to check that
// nodes of binary tree form AP/GP/HP
#include <bits/stdc++.h>
using namespace std;
// Structure of the
// node of the binary tree
struct Node {
int data;
struct Node *left, *right;
};
// Function to find the size
// of the Binary Tree
int size(Node* node)
{
// Base Case
if (node == NULL)
return 0;
else
return (size(node->left) + 1 + size(node->right));
}
// Function to check if the permutation
// of the sequence form Arithmetic Progression
bool checkIsAP(double arr[], int n)
{
// If the sequence contains
// only one element
if (n == 1)
return true;
// Sorting the array
sort(arr, arr + n);
double d = arr[1] - arr[0];
// Loop to check if the sequence
// have same common difference
// between its consecutive elements
for (int i = 2; i < n; i++)
if (arr[i] - arr[i - 1] != d)
return false;
return true;
}
// Function to check if the permutation
// of the sequence form
// Geometric progression
bool checkIsGP(double arr[], int n)
{
// Condition when the length
// of the sequence is 1
if (n == 1)
return true;
// Sorting the array
sort(arr, arr + n);
double r = arr[1] / arr[0];
// Loop to check if the
// sequence have same common
// ratio in consecutive elements
for (int i = 2; i < n; i++) {
if (arr[i] / arr[i - 1] != r)
return false;
}
return true;
}
// Function to check if the permutation
// of the sequence form
// Harmonic Progression
bool checkIsHP(double arr[], int n)
{
// Condition when length of
// sequence in 1
if (n == 1) {
return true;
}
double rec[n];
// Loop to find the reciprocal
// of the sequence
for (int i = 0; i < n; i++) {
rec[i] = ((1 / arr[i]));
}
// Sorting the array
sort(rec, rec + n);
double d = (rec[1]) - (rec[0]);
// Loop to check if the common
// difference of the sequence is same
for (int i = 2; i < n; i++) {
if (rec[i] - rec[i - 1] != d) {
return false;
}
}
return true;
}
// Function to check if the nodes
// of the Binary tree forms AP/GP/HP
void checktype(Node* root)
{
int n = size(root);
double arr[n];
int i = 0;
// Base Case
if (root == NULL)
return;
// Create an empty queue
// for level order traversal
queue<Node*> q;
// Enqueue Root and initialize height
q.push(root);
// Loop to traverse the tree using
// Level order Traversal
while (q.empty() == false) {
Node* node = q.front();
arr[i] = node->data;
i++;
q.pop();
// Enqueue left child
if (node->left != NULL)
q.push(node->left);
// Enqueue right child
if (node->right != NULL)
q.push(node->right);
}
int flag = 0;
// Condition to check if the
// sequence form Arithmetic Progression
if (checkIsAP(arr, n)) {
cout << "Arithmetic Progression"
<< endl;
flag = 1;
}
// Condition to check if the
// sequence form Geometric Progression
else if (checkIsGP(arr, n)) {
cout << "Geometric Progression"
<< endl;
flag = 1;
}
// Condition to check if the
// sequence form Geometric Progression
else if (checkIsHP(arr, n)) {
cout << "Geometric Progression"
<< endl;
flag = 1;
}
else if (flag == 0) {
cout << "No";
}
}
// Function to create new node
struct Node* newNode(int data)
{
struct Node* node = new Node;
node->data = data;
node->left = node->right = NULL;
return (node);
}
// Driver Code
int main()
{
/* Constructed Binary tree is:
1
/ \
2 3
/ \ \
4 5 8
/ \
6 7
*/
struct Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->right = newNode(8);
root->right->right->left = newNode(6);
root->right->right->right = newNode(7);
checktype(root);
return 0;
}
Java
// Java implementation to check that
// nodes of binary tree form AP/GP/HP
import java.util.*;
class GFG {
// Structure of the
// node of the binary tree
static class Node {
int data;
Node left, right;
Node(int data) {
this.data = data;
this.left = this.right = null;
}
};
// Function to find the size
// of the Binary Tree
static int size(Node node) {
// Base Case
if (node == null)
return 0;
else
return (size(node.left) + 1 + size(node.right));
}
// Function to check if the permutation
// of the sequence form Arithmetic Progression
static boolean checkIsAP(double[] arr, int n) {
// If the sequence contains
// only one element
if (n == 1)
return true;
// Sorting the array
Arrays.sort(arr);
double d = arr[1] - arr[0];
// Loop to check if the sequence
// have same common difference
// between its consecutive elements
for (int i = 2; i < n; i++)
if (arr[i] - arr[i - 1] != d)
return false;
return true;
}
// Function to check if the permutation
// of the sequence form
// Geometric progression
static boolean checkIsGP(double[] arr, int n) {
// Condition when the length
// of the sequence is 1
if (n == 1)
return true;
// Sorting the array
Arrays.sort(arr);
double r = arr[1] / arr[0];
// Loop to check if the
// sequence have same common
// ratio in consecutive elements
for (int i = 2; i < n; i++) {
if (arr[i] / arr[i - 1] != r)
return false;
}
return true;
}
// Function to check if the permutation
// of the sequence form
// Harmonic Progression
static boolean checkIsHP(double[] arr, int n) {
// Condition when length of
// sequence in 1
if (n == 1) {
return true;
}
double[] rec = new double[n];
// Loop to find the reciprocal
// of the sequence
for (int i = 0; i < n; i++) {
rec[i] = ((1 / arr[i]));
}
// Sorting the array
Arrays.sort(rec);
double d = (rec[1]) - (rec[0]);
// Loop to check if the common
// difference of the sequence is same
for (int i = 2; i < n; i++) {
if (rec[i] - rec[i - 1] != d) {
return false;
}
}
return true;
}
// Function to check if the nodes
// of the Binary tree forms AP/GP/HP
static void checktype(Node root) {
int n = size(root);
double[] arr = new double[n];
int i = 0;
// Base Case
if (root == null)
return;
// Create an empty queue
// for level order traversal
Queue<Node> q = new LinkedList<>();
// Enqueue Root and initialize height
q.add(root);
// Loop to traverse the tree using
// Level order Traversal
while (q.isEmpty() == false) {
Node node = q.poll();
arr[i] = node.data;
i++;
// Enqueue left child
if (node.left != null)
q.add(node.left);
// Enqueue right child
if (node.right != null)
q.add(node.right);
}
int flag = 0;
// Condition to check if the
// sequence form Arithmetic Progression
if (checkIsAP(arr, n)) {
System.out.println("Arithmetic Progression");
flag = 1;
}
// Condition to check if the
// sequence form Geometric Progression
else if (checkIsGP(arr, n)) {
System.out.println("Geometric Progression");
flag = 1;
}
// Condition to check if the
// sequence form Geometric Progression
else if (checkIsHP(arr, n)) {
System.out.println("Geometric Progression");
flag = 1;
} else if (flag == 0) {
System.out.println("No");
}
}
// Driver Code
public static void main(String[] args) {
/* Constructed Binary tree is:
1
/ \
2 3
/ \ \
4 5 8
/ \
6 7
*/
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.right = new Node(8);
root.right.right.left = new Node(6);
root.right.right.right = new Node(7);
checktype(root);
}
}
// This code is contributed by
// sanjeev2552
Python3
# Python implementation to check that
# nodes of binary tree form AP/GP/HP
# class of the
# node of the binary tree
class Node:
def __init__(self, key):
self.left = None
self.right = None
self.data = key
# Function to find the size
# of the Binary Tree
def size(node):
# Base Case
if node == None:
return 0
else:
return (size(node.left) + 1 + size(node.right))
# Function to check if the permutation
# of the sequence form Arithmetic Progression
def checkIsAP(arr, n):
# If the sequence contains
# only one element
if n == 1:
return 1
# Sorting the array
arr.sort()
d = arr[1] - arr[0]
# Loop to check if the sequence
# have same common difference
# between its consecutive elements
for i in range(2, n):
if (arr[i] - arr[i - 1] != d):
return 0
return 1
# Function to check if the permutation
# of the sequence form
# Geometric progression
def checkIsGP(arr, n):
# Condition when the length
# of the sequence is 1
if (n == 1):
return 1
# Sorting the array
arr.sort()
r = arr[1] / arr[0]
# Loop to check if the
# sequence have same common
# ratio in consecutive elements
for i in range(2, n):
if (arr[i] / arr[i - 1] != r):
return 0
return 1
# Function to check if the permutation
# of the sequence form
# Harmonic Progression
def checkIsHP(arr, n):
# Condition when length of
# sequence in 1
if (n == 1):
return 1
rec = [None] * n
# Loop to find the reciprocal
# of the sequence
for i in range(0, n):
rec[i] = ((1 / arr[i]))
# Sorting the array
rec.sort()
d = (rec[1]) - (rec[0])
# Loop to check if the common
# difference of the sequence is same
for i in range(2, n):
if (rec[i] - rec[i - 1] != d):
return 0
return 1
# Function to check if the nodes
# of the Binary tree forms AP/GP/HP
def checktype(root):
n = size(root)
arr = [Node] * n
i = 0
# Base Case
if (root == None):
return
# Create an empty queue
# for level order traversal
q = []
# Enqueue Root and initialize height
q.append(root)
# Loop to traverse the tree using
# Level order Traversal
while (len(q) > 0):
node = q[0]
arr[i] = node.data
i = i + 1
q.pop(0)
# Enqueue left child
if (node.left != None):
q.append(node.left)
# Enqueue right child
if (node.right != None):
q.append(node.right)
flag = 0
# Condition to check if the
# sequence form Arithmetic Progression
if (checkIsAP(arr, n)):
print("Arithmetic Progression\n")
flag = 1
# Condition to check if the
# sequence form Geometric Progression
elif (checkIsGP(arr, n)):
print("Geometric Progression\n")
flag = 1
# Condition to check if the
# sequence form Geometric Progression
elif (checkIsHP(arr, n)):
print("Harmonicc Progression\n")
flag = 1
elif (flag == 0):
print("No")
# Driver Code
# Constructed Binary tree is:
# 1
# / \
# 2 3
# / \ \
# 4 5 8
# / \
# 6 7
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.right = Node(8)
root.right.right.left = Node(6)
root.right.right.right = Node(7)
checktype(root)
# This code is contributed by rj13to.
C#
// C# implementation to check that
// nodes of binary tree form AP/GP/HP
using System;
using System.Collections.Generic;
public class GFG {
// Structure of the
// node of the binary tree
public class Node {
public int data;
public Node left, right;
public Node(int data) {
this.data = data;
this.left = this.right = null;
}
};
// Function to find the size
// of the Binary Tree
static int size(Node node) {
// Base Case
if (node == null)
return 0;
else
return (size(node.left) + 1 + size(node.right));
}
// Function to check if the permutation
// of the sequence form Arithmetic Progression
static bool checkIsAP(double[] arr, int n) {
// If the sequence contains
// only one element
if (n == 1)
return true;
// Sorting the array
Array.Sort(arr);
double d = arr[1] - arr[0];
// Loop to check if the sequence
// have same common difference
// between its consecutive elements
for (int i = 2; i < n; i++)
if (arr[i] - arr[i - 1] != d)
return false;
return true;
}
// Function to check if the permutation
// of the sequence form
// Geometric progression
static bool checkIsGP(double[] arr, int n) {
// Condition when the length
// of the sequence is 1
if (n == 1)
return true;
// Sorting the array
Array.Sort(arr);
double r = arr[1] / arr[0];
// Loop to check if the
// sequence have same common
// ratio in consecutive elements
for (int i = 2; i < n; i++) {
if (arr[i] / arr[i - 1] != r)
return false;
}
return true;
}
// Function to check if the permutation
// of the sequence form
// Harmonic Progression
static bool checkIsHP(double[] arr, int n) {
// Condition when length of
// sequence in 1
if (n == 1) {
return true;
}
double[] rec = new double[n];
// Loop to find the reciprocal
// of the sequence
for (int i = 0; i < n; i++) {
rec[i] = ((1 / arr[i]));
}
// Sorting the array
Array.Sort(rec);
double d = (rec[1]) - (rec[0]);
// Loop to check if the common
// difference of the sequence is same
for (int i = 2; i < n; i++) {
if (rec[i] - rec[i - 1] != d) {
return false;
}
}
return true;
}
// Function to check if the nodes
// of the Binary tree forms AP/GP/HP
static void checktype(Node root) {
int n = size(root);
double[] arr = new double[n];
int i = 0;
// Base Case
if (root == null)
return;
// Create an empty queue
// for level order traversal
Queue<Node> q = new Queue<Node>();
// Enqueue Root and initialize height
q.Enqueue(root);
// Loop to traverse the tree using
// Level order Traversal
while (q.Count!=0 == false) {
Node node = q.Dequeue();
arr[i] = node.data;
i++;
// Enqueue left child
if (node.left != null)
q.Enqueue(node.left);
// Enqueue right child
if (node.right != null)
q.Enqueue(node.right);
}
int flag = 0;
// Condition to check if the
// sequence form Arithmetic Progression
if (checkIsAP(arr, n)) {
Console.WriteLine("Arithmetic Progression");
flag = 1;
}
// Condition to check if the
// sequence form Geometric Progression
else if (checkIsGP(arr, n)) {
Console.WriteLine("Geometric Progression");
flag = 1;
}
// Condition to check if the
// sequence form Geometric Progression
else if (checkIsHP(arr, n)) {
Console.WriteLine("Geometric Progression");
flag = 1;
} else if (flag == 0) {
Console.WriteLine("No");
}
}
// Driver Code
public static void Main(String[] args) {
/* Constructed Binary tree is:
1
/ \
2 3
/ \ \
4 5 8
/ \
6 7
*/
Node root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.right = new Node(8);
root.right.right.left = new Node(6);
root.right.right.right = new Node(7);
checktype(root);
}
}
// This code contributed by sapnasingh4991
JavaScript
<script>
// JavaScript implementation to check that
// nodes of binary tree form AP/GP/HP
// Structure of the
// node of the binary tree
class Node {
constructor(data) {
this.left = null;
this.right = null;
this.data = data;
}
}
// Function to find the size
// of the Binary Tree
function size(node) {
// Base Case
if (node == null)
return 0;
else
return (size(node.left) + 1 + size(node.right));
}
// Function to check if the permutation
// of the sequence form Arithmetic Progression
function checkIsAP(arr, n) {
// If the sequence contains
// only one element
if (n == 1)
return true;
// Sorting the array
arr.sort();
let d = arr[1] - arr[0];
// Loop to check if the sequence
// have same common difference
// between its consecutive elements
for (let i = 2; i < n; i++)
if (arr[i] - arr[i - 1] != d)
return false;
return true;
}
// Function to check if the permutation
// of the sequence form
// Geometric progression
function checkIsGP(arr, n) {
// Condition when the length
// of the sequence is 1
if (n == 1)
return true;
// Sorting the array
arr.sort();
let r = arr[1] / arr[0];
// Loop to check if the
// sequence have same common
// ratio in consecutive elements
for (let i = 2; i < n; i++) {
if (arr[i] / arr[i - 1] != r)
return false;
}
return true;
}
// Function to check if the permutation
// of the sequence form
// Harmonic Progression
function checkIsHP(arr, n) {
// Condition when length of
// sequence in 1
if (n == 1) {
return true;
}
let rec = new Array(n);
// Loop to find the reciprocal
// of the sequence
for (let i = 0; i < n; i++) {
rec[i] = ((1 / arr[i]));
}
// Sorting the array
rec.sort();
let d = (rec[1]) - (rec[0]);
// Loop to check if the common
// difference of the sequence is same
for (let i = 2; i < n; i++) {
if (rec[i] - rec[i - 1] != d) {
return false;
}
}
return true;
}
// Function to check if the nodes
// of the Binary tree forms AP/GP/HP
function checktype(root) {
let n = size(root);
let arr = new Array(n);
let i = 0;
// Base Case
if (root == null)
return;
// Create an empty queue
// for level order traversal
let q = [];
// Enqueue Root and initialize height
q.push(root);
// Loop to traverse the tree using
// Level order Traversal
while (q.length > 0) {
let node = q[0];
q.shift();
arr[i] = node.data;
i++;
// Enqueue left child
if (node.left != null)
q.push(node.left);
// Enqueue right child
if (node.right != null)
q.push(node.right);
}
let flag = 0;
// Condition to check if the
// sequence form Arithmetic Progression
if (checkIsAP(arr, n)) {
document.write("Arithmetic Progression");
flag = 1;
}
// Condition to check if the
// sequence form Geometric Progression
else if (checkIsGP(arr, n)) {
document.write("Geometric Progression");
flag = 1;
}
// Condition to check if the
// sequence form Geometric Progression
else if (checkIsHP(arr, n)) {
document.write("Geometric Progression");
flag = 1;
} else if (flag == 0) {
document.write("No");
}
}
/* Constructed Binary tree is:
1
/ \
2 3
/ \ \
4 5 8
/ \
6 7
*/
let root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.right = new Node(8);
root.right.right.left = new Node(6);
root.right.right.right = new Node(7);
checktype(root);
</script>
Output: Arithmetic Progression
Performance Analysis:
- Time Complexity: As in the above approach, there is a traversal of the nodes and sorting them which takes O(N*logN) time in worst case. Hence the Time Complexity will be O(N*logN).
- Auxiliary Space Complexity: As in the above approach, There is extra space used to store the data of the nodes. Hence the auxiliary space complexity will be 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