Clockwise Triangular traversal of a Binary Tree


In this problem, we will create a complete binary tree and traverse it in a circular clockwise direction.

For the clockwise traversal, we can think of traversing the boundaries of the tree. For example, we can traverse the outer boundary of the tree first. After that, we can remove visited nodes and traverse the inner boundary of the tree. In this way, we need to make min(height/2, width/2) traversal of the given binary tree.

Problem Statement

We have given a complete binary tree containing N nodes and need to traverse it in a clockwise direction.

Sample Examples

Input

n = 3
	1
 /   \
2     3

Output

1, 3, 2

Explanation

The clockwise traversal is 1, 3, and 2.

Input

n = 7
     1
   /   \
   2    3
 /  \  /  \
4   5 6    7

Output

1, 3, 7, 6, 5, 4, 2

Explanation

First, we traversed the right boundary, after that bottom boundary, and after that left boundary.

Input

n = 11
         1
	   /     \
     2       3
	/   \    /  \
  4    5   6    7
 / \  / \
8  9 10  11

Output

1, 3, 7, 11, 10, 9, 8, 4, 2, 6, 5

Explanation

It traverses in a circular clockwise manner. We need to keep traversing the inner nodes.

Approach 1

In this approach, we will use the list to create a complete binary tree. After that, we will create a two dimensions list and use it to store the list containing nodes of each level separately. Also, we will find the height of the binary tree.

After that, we will traverse the tree's right, bottom, and left boundary. Also, we will make totalLevels/2 circular iterations to traverse all levels circularly.

Algorithm

  • Step 1 − Execute the createBinaryTree() function to create a complete binary tree having n nodes.

  • Step 1.2 − In the createBinaryTree() function, use the for loop to make traversal and define the 'isChild' with a false value inside the loop.

  • Step 1.3 − If 2*p is less than or equal to n, add an edge between the p and 2*p node. Here, we use the vector list to create a binary tree. So, insert the p at the 2*p position to add an edge between p and 2*p. Also, set isChild to true.

  • Step 1.4 − If 2*p + 1 is less than or equal to n, insert an edge between the p and 2*p + 1 nodes. Also, update isChild to true.

  • Step 1.5 − If isChild is false, break the loop.

  • Step 2 − Now, call the executeBFS() function to get nodes of each level in the list.

  • Step 2.1 − Define the queue to store the pair of a single node and its parent node. Also, insert the head node into the queue. Also, use the nodes[][] list to store the node of each level. The visited[] list is used to mark visited nodes with true boolean value. The level[] list stores the level number of each node.

  • Step 2.2 − Traverse the queue.

  • Step 2.3 − Pop the first pair from the queue and mark the node visited.

  • Step 2.4 − Traverse all adjacent nodes of the current node.

  • Step 2.4.1 − If the adjacent node is not visited, insert it into the queue with its parent node. Also, store the level of the child node in the level[] list.

  • Step 2.4.2 − Update the max_level value if it is lower than the level[child].

  • Step 2.4.3 − Push the current node into the nodes[level[child]] list.

    Now, we got each node of the tree in the nodes[][] list according to its level.

  • Step 3 − Call the showClockWise() function to traverse the tree in the clockwise direction.

  • Step 3.1 − Define the levelNo, and cycle variables and initialize them with 0.

  • Step 3.2 − Make iterations while cycle - 1 <= max_level / 2 condition is true.

  • Step 3.3 − Next, we need to traverse the right boundary. So, make iterations using the loop until levelNo is less than maxLevel − cycle. Also, get the last node from the nodes[levelNo] list, print its value, and increment the levelNo by 1.

  • Step 3.4 − Now, we need to traverse the bottom of the tree.

  • Step 3.5 − If levelNo == max_level − cycle condition is true, traverse the bottom nodes.

  • Step 3.6 − Traverse the left boundary of the tree. It can be an inner or outer boundary based on the value of the 'cycle' variable.

  • Step 3.7 − Increment the cycle value by 1, and update the levelNo with the cycle + 1.

Example

#include <bits/stdc++.h>
using namespace std;

void insertEdge(int start, int end, vector<int> tree[]) {
   tree[start].push_back(end);
   tree[end].push_back(start);
}
void createBinaryTree(int n, vector<int> tree[]) {
   // Create a complete binary tree
   for (int p = 1;; p++) {
      // Add edges to the tree
      bool isChild = false;
      if (2 * p <= n) {
         insertEdge(p, 2 * p, tree);
         isChild = true;
      }
      if (2 * p + 1 <= n) {
         insertEdge(p, 2 * p + 1, tree);
         isChild = true;
      }
      if (!isChild)
         break;
   }
}
void executeBFS(int root, vector<int> tree[], bool visited[], int level[], vector<int> nodes[], int &max_level) {
   queue<pair<int, int>> que;
   // Inserting the root node in the queue and mark it as visited
   que.push({root, 0});
   nodes[0].push_back(root);
   visited[root] = true;
   level[1] = 0;
   while (!que.empty()) {
      pair<int, int> temp = que.front();
      que.pop();
      visited[temp.first] = true;
      // Get adjacent vertices
      for (int child : tree[temp.first]) {
         if (!visited[child]) {
            que.push({child, temp.first});
            level[child] = level[temp.first] + 1;
            // Updating the max level
            max_level = max(max_level, level[child]);
            // Store nodes according to level wise
            nodes[level[child]].push_back(child);
         }
      }
   }
}
void showClockWise(vector<int> nodes[], int max_level) {
   int levelNo = 0, cycle = 0;
   while (cycle - 1 <= max_level / 2) {
      // Traverse right nodes
      while (levelNo < max_level - cycle) {
         int q = nodes[levelNo].size() - 1;
         cout << nodes[levelNo][q - cycle] << " ";
         levelNo++;
      }
      // Traverse bottom nodes from right -> left
      if (levelNo == max_level - cycle) {
         int q = nodes[levelNo].size() - 1;
         for (q -= cycle; q >= cycle; q--)
            cout << nodes[levelNo][q] << " ";
      }
      levelNo--;
      // Traverse left nodes
      while (levelNo > cycle) {
         cout << nodes[levelNo][cycle] << " ";
         levelNo--;
      }
      // Increment cycle
      cycle++;
      // Update next level to start from
      levelNo = cycle + 1;
   }
}
int main() {
   // Number of vertices
   int n = 7;
   const int size = 1e5;
   int max_level = 0;
   vector<int> tree[size + 1];
   bool visited[size + 1];
   int level[size + 1];
   vector<int> nodes[size + 1];
   createBinaryTree(n, tree);
   executeBFS(1, tree, visited, level, nodes, max_level);
   showClockWise(nodes, max_level);
   return 0;
}

Output

1 3 7 6 5 4 2
  • Time complexity − O(N)

  • Space complexity − O(N)

Conclusion

Programmers may try to traverse the binary tree in the anti-clockwise direction. For that, they can traverse the left boundary first, the bottom one after, and the right one at last. Also, they can traverse inner boundaries one by one, as we have done in this problem.

Updated on: 25-Aug-2023

78 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements