Check whether nodes of Binary Tree form Arithmetic, Geometric or Harmonic Progression

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.

Below is the implementation of the above approach:

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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 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 tarversal
    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;
}
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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 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 tarversal
        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: 
                 
                / \ 
               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
chevron_right

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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 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 tarversal
        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: 
                 
                / \ 
               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
chevron_right

Output:
Arithmetic Progression

Performance Analysis:

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.





Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : sanjeev2552, sapnasingh4991

Article Tags :