Posted on by Kalkicode
Code Queue

Construct Diamond Tree

The Construct Diamond Tree problem involves creating a special binary tree known as a Diamond Tree. A Diamond Tree is a unique binary tree where each node has two children, forming a diamond pattern. The goal is to construct this tree and then print its elements in a specific level order.

Problem Statement

Given an integer k, the task is to construct a Diamond Tree of k levels and then print its elements in a specific level order.

Example

Let's consider k = 4:

The constructed Diamond Tree would look like this:

Diamond Tree

The printed level order of the Diamond Tree would be:

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

Idea to Solve

The problem can be solved by constructing the Diamond Tree using a queue-based approach. The main idea is to iteratively add nodes to the queue, constructing the tree level by level. Then, print the elements in a level-wise manner.

Algorithm

  1. Initialize a queue to hold tree nodes.
  2. Create the root node with the value 1.
  3. Enqueue the root node into the queue.
  4. Loop while k is greater than 1 (to construct the Diamond Tree):
    • Get the current size of the queue (n).
    • Loop n times:
      • Dequeue a node from the queue.
      • Create left and right children nodes with values num + 1 and num + 2.
      • Enqueue the left and right children nodes into the queue.
      • Increment num by 2.
    • Decrement k by 1.
  5. Loop while the queue size is greater than 1 (to construct the bottom part of the Diamond Tree):
    • Dequeue a node (first node).
    • Dequeue another node (second node).
    • Create a new node with the sum of the keys of the two dequeued nodes.
    • Connect the new node to the right side of the first dequeued node.
    • Connect the new node to the left side of the second dequeued node.
    • Enqueue the new node into the queue.
  6. Print the elements of the Diamond Tree in a level order:
    • Enqueue the root node into the queue.
    • While the queue is not empty:
      • Get the current size of the queue (n).
      • Loop n times:
        • Dequeue a node from the queue.
        • Enqueue its left and right children if they exist and are not the same as the previously dequeued node.
        • Print the key of the dequeued node.
    • Move to the next line to signify a change in levels.

Code Solution

Time Complexity

The time complexity of constructing the Diamond Tree and printing it in level order is O(N), where N is the total number of nodes in the Diamond Tree. This is because each node is enqueued and dequeued exactly once during the construction and traversal processes.

Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment