Generate an array representing GCD of nodes of each vertical level of a Binary Tree
Last Updated :
01 Jul, 2021
Given a Binary Tree, the task is to construct an array such that ith index of the array contains GCD of all the nodes present at the ith vertical level of the given binary tree.
Examples:
Input: Below is the given Tree:
5
/ \
4 7
/ \ \
8 10 6
\
8
Output: {8, 4, 5, 7, 6}
Explanation:
Vertical level I -> GCD(8) = 8.
Vertical level II -> GCD(4, 8) = 4.
Vertical level II -> GCD(5, 10) = 5.
Vertical level IV -> GCD(7) = 7.
Verticleal level V -> GCD(6) = 6
Input: Below is the given Tree:
4
/ \
2 3
/ \ / \
3 2 4 5
Output: {3, 2, 2, 3, 5}
Approach: The given problem can be solved by performing the vertical order traversal of the given tree and stores each node's value that occurs in the same vertical lines and then print the GCD of all the values stored for each level. Follow the below steps to solve this problem:
- Initialize a Map M to store the GCD of all the nodes for each vertical line while performing the traversal.
- Initialize a variable, say hd as 0 to keep track of the horizontal distance.
- Recursively traverse the given tree and perform the following steps:
- Store the current node's values in the map M as the key as hd and value as node's value.
- Decrement the variable hd by 1 and recursively call for the left subtree.
- Increment the variable hd by 1 and recursively call for the right subtree.
- Traverse the map and find the GCD of all the nodes stored in the map for each horizontal distance as the key and print the GCD value obtained.
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Class for node of binary tree
struct TreeNode
{
int val;
TreeNode *left, *right;
TreeNode(int x)
{
val = x;
left = right = NULL;
}
};
// Function to find GCD of two numbers
int GCD(int a, int b)
{
if (!b)
return a;
// Recursively find the GCD
return GCD(b, a % b);
}
// Stores the element for each
// vertical distance
unordered_map<int, int> mp;
// Function to traverse the tree
void Trav(TreeNode *root, int hd)
{
if (!root)
return;
// Store the values in the map
if (mp[hd] == 0)
mp[hd] = root->val;
else
mp[hd] = GCD(mp[hd], root->val);
// Recursive Calls
Trav(root->left, hd - 1);
Trav(root->right, hd + 1);
}
// Function to construct array from
// vertically positioned nodes
void constructArray(TreeNode *root)
{
Trav(root, 0);
// Get range of horizontal distances
int lower = INT_MAX, upper = 0;
for(auto it:mp)
{
lower = min(lower, it.first);
upper = max(upper, it.first);
}
vector<int> ans;
// Extract the array of values
for(int i = lower; i < upper + 1; i++)
ans.push_back(mp[i]);
// Print the constructed array
cout << "[";
for(int i = 0; i < ans.size() - 1; i++)
cout << ans[i] << ", ";
cout << ans[ans.size() - 1] << "]";
}
// Driver code
int main()
{
TreeNode *root = new TreeNode(5);
root->left = new TreeNode(4);
root->right = new TreeNode(7);
root->left->left = new TreeNode(8);
root->left->left->right = new TreeNode(8);
root->left->right = new TreeNode(10);
root->right->right = new TreeNode(6);
// Function Call
constructArray(root);
return 0;
}
// This code is contributed by mohit kumar 29
Java
// Java program for the above approach
import java.lang.*;
import java.util.*;
// Class containing the left and right
// child of current node and the
// key value
class Node
{
int val;
Node left, right;
// Constructor of the class
public Node(int item)
{
val = item;
left = right = null;
}
}
class GFG{
Node root;
// Stores the element for each
// vertical distance
static Map<Integer, Integer> mp = new HashMap<>();
// Function to find GCD of two numbers
static int GCD(int a, int b)
{
if (b == 0)
return a;
// Recursively find the GCD
return GCD(b, a % b);
}
// Function to traverse the tree
static void Trav(Node root, int hd)
{
if (root == null)
return;
// Store the values in the map
if (!mp.containsKey(hd))
mp.put(hd, root.val);
else
mp.put(hd, GCD(mp.get(hd), root.val));
// Recursive Calls
Trav(root.left, hd - 1);
Trav(root.right, hd + 1);
}
// Function to construct array from
// vertically positioned nodes
static void constructArray(Node root)
{
Trav(root, 0);
// Get range of horizontal distances
int lower = Integer.MAX_VALUE, upper = 0;
for(Map.Entry<Integer, Integer> it:mp.entrySet())
{
lower = Math.min(lower, it.getKey());
upper = Math.max(upper, it.getKey());
}
ArrayList<Integer> ans = new ArrayList<>();
// Extract the array of values
for(int i = lower; i < upper + 1; i++)
ans.add(mp.getOrDefault(i,0));
// Print the constructed array
System.out.print("[");
for(int i = 0; i < ans.size() - 1; i++)
System.out.print(ans.get(i) + ", ");
System.out.print(ans.get(ans.size() - 1) + "]");
}
// Driver code
public static void main(String[] args)
{
GFG tree = new GFG();
Node root = new Node(5);
root.left = new Node(4);
root.right = new Node(7);
root.left.left = new Node(8);
root.left.left.right = new Node(8);
root.left.right = new Node(10);
root.right.right = new Node(6);
// Function Call
constructArray(root);
}
}
// This code is contributed by offbeat
Python3
# Python3 program for the above approach
# Class for node of binary tree
class TreeNode:
def __init__(self, val ='', left = None, right = None):
self.val = val
self.left = left
self.right = right
# Function to find GCD of two numbers
def GCD(a, b):
if not b:
return a
# Recursively find the GCD
return GCD(b, a % b)
# Function to construct array from
# vertically positioned nodes
def constructArray(root):
# Stores the element for each
# vertical distance
mp = {}
# Function to traverse the tree
def Trav(root, hd):
if not root:
return
# Store the values in the map
if hd not in mp:
mp[hd] = root.val
else:
mp[hd] = GCD(mp[hd], root.val)
# Recursive Calls
Trav(root.left, hd-1)
Trav(root.right, hd + 1)
Trav(root, 0)
# Get range of horizontal distances
lower = min(mp.keys())
upper = max(mp.keys())
ans = []
# Extract the array of values
for i in range(lower, upper + 1):
ans.append(mp[i])
# Print the constructed array
print(ans)
# Driver Code
# Given Tree
root = TreeNode(5)
root.left = TreeNode(4)
root.right = TreeNode(7)
root.left.left = TreeNode(8)
root.left.left.right = TreeNode(8)
root.left.right = TreeNode(10)
root.right.right = TreeNode(6)
# Function Call
constructArray(root)
C#
// C# program for the above approach
using System;
using System.Collections.Generic;
// Class containing the left and right
// child of current node and the
// key value
public class Node
{
public int val;
public Node left, right;
// Constructor of the class
public Node(int item)
{
val = item;
left = right = null;
}
}
class GFG{
// Stores the element for each
// vertical distance
static Dictionary<int,
int> mp = new Dictionary<int,
int>();
// Function to find GCD of two numbers
static int GCD(int a, int b)
{
if (b == 0)
return a;
// Recursively find the GCD
return GCD(b, a % b);
}
// Function to traverse the tree
static void Trav(Node root, int hd)
{
if (root == null)
return;
// Store the values in the map
if (!mp.ContainsKey(hd))
mp.Add(hd, root.val);
else
mp[hd] = GCD(mp[hd], root.val);
// Recursive Calls
Trav(root.left, hd - 1);
Trav(root.right, hd + 1);
}
// Function to construct array from
// vertically positioned nodes
static void constructArray(Node root)
{
Trav(root, 0);
// Get range of horizontal distances
int lower = Int32.MaxValue, upper = 0;
foreach(KeyValuePair<int, int> it in mp)
{
lower = Math.Min(lower, it.Key);
upper = Math.Max(upper, it.Key);
}
List<int> ans = new List<int>();
// Extract the array of values
for(int i = lower; i < upper + 1; i++)
if(mp.ContainsKey(i))
ans.Add(mp[i]);
else
ans.Add(0);
// Print the constructed array
Console.Write("[");
for(int i = 0; i < ans.Count - 1; i++)
Console.Write(ans[i] + ", ");
Console.Write(ans[ans.Count - 1] + "]");
}
// Driver code
static public void Main()
{
Node root = new Node(5);
root.left = new Node(4);
root.right = new Node(7);
root.left.left = new Node(8);
root.left.left.right = new Node(8);
root.left.right = new Node(10);
root.right.right = new Node(6);
// Function Call
constructArray(root);
}
}
// This code is contributed by rishavmahato348
JavaScript
<script>
// Javascript program for the above approach
// Class containing the left and right
// child of current node and the
// key value
class Node
{
constructor(item) {
this.left = null;
this.right = null;
this.val = item;
}
}
// Stores the element for each
// vertical distance
let mp = new Map();
// Function to find GCD of two numbers
function GCD(a, b)
{
if (b == 0)
return a;
// Recursively find the GCD
return GCD(b, a % b);
}
// Function to traverse the tree
function Trav(root, hd)
{
if (root == null)
return;
// Store the values in the map
if (!mp.has(hd))
mp.set(hd, root.val);
else
mp.set(hd, GCD(mp.get(hd), root.val));
// Recursive Calls
Trav(root.left, hd - 1);
Trav(root.right, hd + 1);
}
// Function to construct array from
// vertically positioned nodes
function constructArray(root)
{
Trav(root, 0);
// Get range of horizontal distances
let lower = Number.MAX_VALUE, upper = 0;
mp.forEach((values,keys)=>{
lower = Math.min(lower, keys);
upper = Math.max(upper, keys);
})
let ans = [];
// Extract the array of values
for(let i = lower; i < upper + 1; i++)
{
if(mp.has(i))
{
ans.push(mp.get(i));
}
else{
ans.push(0);
}
}
// Print the constructed array
document.write("[");
for(let i = 0; i < ans.length - 1; i++)
document.write(ans[i] + ", ");
document.write(ans[ans.length - 1] + "]");
}
let root = new Node(5);
root.left = new Node(4);
root.right = new Node(7);
root.left.left = new Node(8);
root.left.left.right = new Node(8);
root.left.right = new Node(10);
root.right.right = new Node(6);
// Function Call
constructArray(root);
// This code is contributed by suresh07.
</script>
Time Complexity: O(N*log N)
Auxiliary Space: O(N)
Similar Reads
DSA Tutorial - Learn Data Structures and Algorithms DSA (Data Structures and Algorithms) is the study of organizing data efficiently using data structures like arrays, stacks, and trees, paired with step-by-step procedures (or algorithms) to solve problems effectively. Data structures manage how data is stored and accessed, while algorithms focus on
7 min read
Quick Sort QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. It works on the principle of divide and conquer, breaking down the problem into s
12 min read
Merge Sort - Data Structure and Algorithms Tutorials Merge sort is a popular sorting algorithm known for its efficiency and stability. It follows the divide-and-conquer approach. It works by recursively dividing the input array into two halves, recursively sorting the two halves and finally merging them back together to obtain the sorted array. Merge
14 min read
Data Structures Tutorial Data structures are the fundamental building blocks of computer programming. They define how data is organized, stored, and manipulated within a program. Understanding data structures is very important for developing efficient and effective algorithms. What is Data Structure?A data structure is a st
2 min read
Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir
8 min read
Breadth First Search or BFS for a Graph Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
15+ min read
Binary Search Algorithm - Iterative and Recursive Implementation Binary Search Algorithm is a searching algorithm used in a sorted array by repeatedly dividing the search interval in half. The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(log N). Binary Search AlgorithmConditions to apply Binary Searc
15 min read
Insertion Sort Algorithm Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
9 min read
Array Data Structure Guide In 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
4 min read
Sorting Algorithms A 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