Diamond Tree

Given a number K, the task is to create the Diamond-like structure of Tree which follows these two conditions:

  1. First K levels of the tree should be a balanced binary tree and the value of nodes should start from 1 and increases from left to right.
  2. The next K – 1 levels should form a diamond-like structure by merging every pair of nodes with their sum stored as their child.

Examples:

Input: K = 2
Output:
1 
2 3 
5
Explanation: 
Structre will look like
          1                            
        /   \    
       2     3     
        \   /
          5

For the given value k = 2
First, create a balanced
binary tree of level 2 
with a value starting from 1.
Then on level 3 merge both
the node with a node 
having value 2 + 3 = 5.  

Input: K = 3
Output:
1 
2 3 
4 5 6 7 
9 13 
22
Explanation: 
Structre will look like
          1                            
        /   \    
      2       3     
     /  \    /  \               
    4    5  6    7
     \   /   \  /   
       9      13
        \    /
          22

Input: K = 4 
Output:
1 
2 3 
4 5 6 7 
8 9 10 11 12 13 14 15 
17 21 25 29 
38 54 
92
Explanation: 
Structre will look like
             1                            
        /        \    
      2            3     
     /  \        /    \               
    4    5       6      7
  /  \  /  \    / \    / \
  8   9 10  11 12  13 14  15
  \  /  \  /   \  /    \  / 
   17    21     25      29
     \  /         \    /
      38            54
        \          /
             92    

Approach:



  1. First create the K level balanced binary tree using level order traversal and give values starting from 1 and increasing from left to right.
  2. Now start to merge the level by summing up the two node at a time by using level order
  3. At the end, Print each level of the binary tree

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ programm to create the diamond
// like structre of Binary Tree
// for a given value of K
  
#include <bits/stdc++.h>
using namespace std;
  
// A Tree node
struct Node {
    int data;
    Node* left;
    Node* right;
};
  
// Utility function to create a new node
Node* createNewNode(int value)
{
    Node* temp = NULL;
    temp = new Node();
    temp->data = value;
    temp->left = NULL;
    temp->right = NULL;
    return temp;
}
  
// Utility function to create the diamond
// like structre of Binary tree
void createStructreUtil(queue<Node*>& qu,
                        int k)
{
    int num = 1;
    int level = k - 1;
  
    // Run the outer while loop
    // and create structre up to
    // the k levels
    while (level--) {
  
        int qsize = qu.size();
  
        // Run inner while loop to
        // create current level
        while (qsize--) {
  
            Node* temp = qu.front();
            qu.pop();
            num += 1;
  
            // Create left child
            temp->left = createNewNode(num);
            num += 1;
  
            // Create right child
            temp->right = createNewNode(num);
  
            // Push the left child into
            // the queue
            qu.push(temp->left);
  
            // Push the right child into
            // the queue
            qu.push(temp->right);
        }
    }
    num += 1;
  
    // Run the while loop
    while (qu.size() > 1) {
  
        // Pop first element from the queue
        Node* first = qu.front();
        qu.pop();
  
        // Pop second element from the queue
        Node* second = qu.front();
        qu.pop();
  
        // Create diamond structre
        first->right
            = createNewNode(first->data
                            + second->data);
        second->left = first->right;
  
        // Push the node into the queue
        qu.push(first->right);
    }
}
  
// Function to print the Diamond
// Structre of Binary Tree
void printLevelOrder(Node* root, int k)
{
    // Base Case
    if (root == NULL)
        return;
  
    // Create an empty queue
    queue<Node*> qu;
  
    // Enqueue Root and initialize height
    qu.push(root);
    int level = k - 1;
  
    // while loop to print the element
    // up to the (k - 1) levels
    while (level--) {
  
        int qsize = qu.size();
        while (qsize--) {
  
            Node* temp = qu.front();
            qu.pop();
            cout << temp->data << " ";
  
            // Enqueue left child
            if (temp->left != NULL)
                qu.push(temp->left);
  
            // Enqueue right child
            if (temp->right != NULL)
                qu.push(temp->right);
        }
        cout << endl;
    }
  
    // Loop to print the element
    // rest all level except last
    // level
    while (qu.size() > 1) {
  
        int qsize = qu.size();
        while (qsize) {
  
            Node* first = qu.front();
            qu.pop();
            Node* second = qu.front();
            qu.pop();
            cout << first->data << " "
                 << second->data << " ";
            qu.push(first->right);
            qsize = qsize - 2;
        }
        cout << endl;
    }
  
    // Print the last element
    Node* first = qu.front();
    qu.pop();
    cout << first->data << endl;
}
  
// Function to create the
// structre
void createStructre(int k)
{
    queue<Node*> qu;
    Node* root = createNewNode(1);
    qu.push(root);
  
    // Utility Function call to
    // create structre
    createStructreUtil(qu, k);
    printLevelOrder(root, k);
}
  
// Driver code
int main()
{
    int k = 4;
  
    // Print Structre
    createStructre(k);
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java programm to create the diamond
// like structre of Binary Tree
// for a given value of K
import java.util.*;
  
class GFG{
   
// A Tree node
static class Node {
    int data;
    Node left;
    Node right;
};
   
// Utility function to create a new node
static Node createNewNode(int value)
{
    Node temp = null;
    temp = new Node();
    temp.data = value;
    temp.left = null;
    temp.right = null;
    return temp;
}
   
// Utility function to create the diamond
// like structre of Binary tree
static void createStructreUtil(Queue<Node> qu,
                        int k)
{
    int num = 1;
    int level = k - 1;
   
    // Run the outer while loop
    // and create structre up to
    // the k levels
    while (level-- >0) {
   
        int qsize = qu.size();
   
        // Run inner while loop to
        // create current level
        while (qsize-- > 0) {
   
            Node temp = qu.peek();
            qu.remove();
            num += 1;
   
            // Create left child
            temp.left = createNewNode(num);
            num += 1;
   
            // Create right child
            temp.right = createNewNode(num);
   
            // Push the left child into
            // the queue
            qu.add(temp.left);
   
            // Push the right child into
            // the queue
            qu.add(temp.right);
        }
    }
    num += 1;
   
    // Run the while loop
    while (qu.size() > 1) {
   
        // Pop first element from the queue
        Node first = qu.peek();
        qu.remove();
   
        // Pop second element from the queue
        Node second = qu.peek();
        qu.remove();
   
        // Create diamond structre
        first.right
            = createNewNode(first.data
                            + second.data);
        second.left = first.right;
   
        // Push the node into the queue
        qu.add(first.right);
    }
}
   
// Function to print the Diamond
// Structre of Binary Tree
static void printLevelOrder(Node root, int k)
{
    // Base Case
    if (root == null)
        return;
   
    // Create an empty queue
    Queue<Node> qu = new LinkedList<>();
   
    // Enqueue Root and initialize height
    qu.add(root);
    int level = k - 1;
   
    // while loop to print the element
    // up to the (k - 1) levels
    while (level-- > 0) {
   
        int qsize = qu.size();
        while (qsize-- > 0) {
   
            Node temp = qu.peek();
            qu.remove();
            System.out.print(temp.data+ " ");
   
            // Enqueue left child
            if (temp.left != null)
                qu.add(temp.left);
   
            // Enqueue right child
            if (temp.right != null)
                qu.add(temp.right);
        }
        System.out.println();
    }
   
    // Loop to print the element
    // rest all level except last
    // level
    while (qu.size() > 1) {
   
        int qsize = qu.size();
        while (qsize > 0) {
   
            Node first = qu.peek();
            qu.remove();
            Node second = qu.peek();
            qu.remove();
            System.out.print(first.data+ " "
                 + second.data+ " ");
            qu.add(first.right);
            qsize = qsize - 2;
        }
        System.out.println();
    }
   
    // Print the last element
    Node first = qu.peek();
    qu.remove();
    System.out.print(first.data +"\n");
}
   
// Function to create the
// structre
static void createStructre(int k)
{
    Queue<Node> qu = new LinkedList<>();
    Node root = createNewNode(1);
    qu.add(root);
   
    // Utility Function call to
    // create structre
    createStructreUtil(qu, k);
    printLevelOrder(root, k);
}
   
// Driver code
public static void main(String[] args)
{
    int k = 4;
   
    // Print Structre
    createStructre(k);
}
}
  
// This code is contributed by Rajput-Ji

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# programm to create the diamond
// like structre of Binary Tree
// for a given value of K
using System;
using System.Collections.Generic;
  
class GFG{
    
// A Tree node
class Node {
    public int data;
    public Node left;
    public Node right;
};
    
// Utility function to create a new node
static Node createNewNode(int value)
{
    Node temp = null;
    temp = new Node();
    temp.data = value;
    temp.left = null;
    temp.right = null;
    return temp;
}
    
// Utility function to create the diamond
// like structre of Binary tree
static void createStructreUtil(Queue<Node> qu,
                        int k)
{
    int num = 1;
    int level = k - 1;
    
    // Run the outer while loop
    // and create structre up to
    // the k levels
    while (level-- >0) {
    
        int qsize = qu.Count;
    
        // Run inner while loop to
        // create current level
        while (qsize-- > 0) {
    
            Node temp = qu.Peek();
            qu.Dequeue();
            num += 1;
    
            // Create left child
            temp.left = createNewNode(num);
            num += 1;
    
            // Create right child
            temp.right = createNewNode(num);
    
            // Push the left child into
            // the queue
            qu.Enqueue(temp.left);
    
            // Push the right child into
            // the queue
            qu.Enqueue(temp.right);
        }
    }
    num += 1;
    
    // Run the while loop
    while (qu.Count > 1) {
    
        // Pop first element from the queue
        Node first = qu.Peek();
        qu.Dequeue();
    
        // Pop second element from the queue
        Node second = qu.Peek();
        qu.Dequeue();
    
        // Create diamond structre
        first.right
            = createNewNode(first.data
                            + second.data);
        second.left = first.right;
    
        // Push the node into the queue
        qu.Enqueue(first.right);
    }
}
    
// Function to print the Diamond
// Structre of Binary Tree
static void printLevelOrder(Node root, int k)
{
    // Base Case
    if (root == null)
        return;
    
    // Create an empty queue
    Queue<Node> qu = new Queue<Node>();
    
    // Enqueue Root and initialize height
    qu.Enqueue(root);
    int level = k - 1;
    
    // while loop to print the element
    // up to the (k - 1) levels
    while (level-- > 0) {
    
        int qsize = qu.Count;
        while (qsize-- > 0) {
    
            Node temp = qu.Peek();
            qu.Dequeue();
            Console.Write(temp.data+ " ");
    
            // Enqueue left child
            if (temp.left != null)
                qu.Enqueue(temp.left);
    
            // Enqueue right child
            if (temp.right != null)
                qu.Enqueue(temp.right);
        }
        Console.WriteLine();
    }
    
    // Loop to print the element
    // rest all level except last
    // level
    Node first;
    while (qu.Count > 1) {
    
        int qsize = qu.Count;
        while (qsize > 0) {
    
            first = qu.Peek();
            qu.Dequeue();
            Node second = qu.Peek();
            qu.Dequeue();
            Console.Write(first.data+ " "
                 + second.data+ " ");
            qu.Enqueue(first.right);
            qsize = qsize - 2;
        }
        Console.WriteLine();
    }
    
    // Print the last element
    first = qu.Peek();
    qu.Dequeue();
    Console.Write(first.data +"\n");
}
    
// Function to create the
// structre
static void createStructre(int k)
{
    Queue<Node> qu = new Queue<Node>();
    Node root = createNewNode(1);
    qu.Enqueue(root);
    
    // Utility Function call to
    // create structre
    createStructreUtil(qu, k);
    printLevelOrder(root, k);
}
    
// Driver code
public static void Main(String[] args)
{
    int k = 4;
    
    // Print Structre
    createStructre(k);
}
}
  
// This code is contributed by Princi Singh

chevron_right


Output:

1 
2 3 
4 5 6 7 
8 9 10 11 12 13 14 15 
17 21 25 29 
38 54 
92

GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details




My Personal Notes arrow_drop_up

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 : Rajput-Ji, princi singh