Middle To Up-Down Order traversal of a Binary Tree

Given a binary tree, the task is to traverse this binary tree from the middle to the up-down order.

In Middle to up-down order traversal, following steps are performed:

  1. First, print the middle level of the tree.
  2. Then, print the elements at one level above the middle level of the tree.
  3. Then, print the elements at one level below the middle level of the tree.
  4. Then, print the elements at two levels above the middle level of the tree.
  5. Then, print the elements at two levels below the middle level of the tree and so on.

Note: In this problem, the middle level is considered at ((H / 2) + 1)th level where H is the height of the tree and the level of the root is considered as 1.

Examples:

Input:
                 10 
               /     \ 
              12     13 
              /       \ 
             14        15 
             / \       / \ 
            21 22     23 24  
Output:
        14, 15, 
        12, 13, 
        21, 22, 23, 24, 
        10,
Explanation:
There are 4 levels in the tree. 
Therefore, Middle level = ((4 / 2) + 1) = 3
Now, the tree is traversed in the following way:
Middle level: 14, 15
One level above the middle level: 12, 13
One level below the middle level: 21, 22, 23, 24
Two levels above the middle level: 10

Input:
                  5 
                /   \ 
              2      13 
            /   \      \
           4    25       6
          /      / \ 
        11       3 21 
                     \
                      9
Output:
        4, 25, 6 
        2, 13 
        11, 3, 21
        5
        9
Explanation:
There are 5 levels in the tree. 
Therefore, Middle level = ((5 / 2) + 1) = 3.
Now, the tree is traversed in the following way:
Middle level: 4, 25, 6
One level above the middle level: 2, 13
One level below the middle level: 11, 3, 21
Two levels above the middle level: 5
Two levels below the middle level: 9

Approach: The idea is to store the tree in a matrix. In order to do that,



  • The height and width of the tree are computed.
  • After computing the height and maximum width, a 2d matrix is created and a breadth-first search is performed on the tree to store the tree in the matrix.

    For example:

  • Then, simply iterate over the matrix and print the values from the matrix as per the given condition.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to traverse the tree
// from the middle to up and down
  
#include <bits/stdc++.h>
using namespace std;
  
// A Tree node
struct Node {
    int key;
    struct Node *left, *right;
};
  
// Utility function to create
// a new node
Node* newNode(int key)
{
    Node* temp = new Node;
    temp->key = key;
    temp->left = temp->right = NULL;
    return (temp);
}
  
// Function to calculate the
// height of the tree
int findHeight(struct Node* node)
{
    // Base condition
    if (node == NULL)
        return 0;
    int leftHeight = findHeight(node->left);
    int rightHeight = findHeight(node->right);
  
    // Return the maximum of the height
    // of the left and right subtree
    return 1 + (leftHeight > rightHeight
                    ? leftHeight
                    : rightHeight);
}
  
// Function to find the width of the tree
void findWidth(struct Node* node, int& maxValue,
               int& minValue, int hd)
{
    // Base cases
    if (node == NULL)
        return;
  
    if (hd > maxValue) {
        maxValue = hd;
    }
  
    if (hd < minValue) {
        minValue = hd;
    }
  
    // Recursively call the function twice to find
    // the maximum width
    findWidth(node->left, maxValue, minValue, hd - 1);
    findWidth(node->right, maxValue, minValue, hd + 1);
}
  
// Function to traverse the tree and
// store level order traversal in a matrix
void BFS(int** mtrx, struct Node* node)
{
    // Create queue for storing
    // the addresses of nodes
    queue<struct Node*> qu;
  
    qu.push(node);
  
    int i = -1, j = -1;
  
    struct Node* poped_node = NULL;
  
    // Iterating over the queue to perform
    // breadth-first search traversal
    while (!qu.empty()) {
  
        i++;
  
        int qsize = qu.size();
  
        while (qsize--) {
            j++;
  
            poped_node = qu.front();
  
            // Store the data of the node into
            // the matrix
            mtrx[i][j] = poped_node->key;
            qu.pop();
  
            // Performing BFS for the remaining
            // nodes in the queue
            if (poped_node->left != NULL) {
                qu.push(poped_node->left);
            }
  
            if (poped_node->right != NULL) {
                qu.push(poped_node->right);
            }
        }
  
        j = -1;
    }
}
  
// Function for Middle to Up Down
// Traversal of Binary Tree
void traverse_matrix(int** mtrx, int height,
                     int width)
{
    // Variables to handle rows and columns
    // of the matrix
    int up = (height / 2);
    int down = up + 1;
  
    bool flag = true;
    int k = 0;
  
    // Print the middle row
    for (int j = 0; j < width; j++) {
        if (mtrx[up][j] != INT_MAX) {
            cout << mtrx[up][j] << ", ";
        }
    }
    cout << endl;
    up--;
  
    // Loop to print the remaining rows
    for (int i = 0; i < (height - 1); i++) {
  
        // Condition to manage up and
        // down indices in the matrix
        if (flag) {
            k = up;
            up--;
            flag = !flag;
        }
  
        else {
            k = down;
            down++;
            flag = !flag;
        }
  
        // Loop to print the value
        // of matrix cells in perticular row
        for (int j = 0; j < width; j++) {
  
            if (mtrx[k][j] != INT_MAX) {
                cout << mtrx[k][j] << ", ";
            }
        }
        cout << endl;
    }
}
  
// A utility function for middle to
// up down traversal
void printPattern(struct Node* node)
{
    // max, min has been taken for
    // calculating the width of tree
    int max_value = INT_MIN;
    int min_value = INT_MAX;
    int hd = 0;
  
    // Calculate the width of a tree
    findWidth(node, max_value, min_value, hd);
    int width = max_value + abs(min_value);
  
    // Calculate the height of the tree
    int height = findHeight(node);
  
    // Double pointer to create 2D array
    int** mtrx = new int*[height];
  
    // Initialize the width for
    // each row of the matrix
    for (int i = 0; i < height; i++) {
        mtrx[i] = new int[width];
    }
  
    // Initialize complete matrix with
    // MAX INTEGER(purpose garbage)
    for (int i = 0; i < height; i++) {
        for (int j = 0; j < width; j++) {
            mtrx[i][j] = INT_MAX;
        }
    }
  
    // Store the BFS traversal of the tree
    // into the 2-D matrix
    BFS(mtrx, node);
  
    // Print the circular clockwise spiral
    // traversal of the tree
    traverse_matrix(mtrx, height, width);
  
    // release extra memory
    // allocated for matrix
    free(mtrx);
}
  
// Driver Code
int main()
{
    /* 
                  10 
               /     \ 
              12     13 
              /       \ 
             14        15 
             / \       / \ 
            21 22     23 24  
    */
  
    // Creating the above tree
    Node* root = newNode(10);
    root->left = newNode(12);
    root->right = newNode(13);
  
    root->right->left = newNode(14);
    root->right->right = newNode(15);
  
    root->right->left->left = newNode(21);
    root->right->left->right = newNode(22);
    root->right->right->left = newNode(23);
    root->right->right->right = newNode(24);
  
    printPattern(root);
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to traverse the tree 
// from the middle to up and down 
import java.util.*;
  
class GFG{ 
  
// A Tree node 
static class Node { 
    int key; 
    Node left, right; 
}; 
static int maxValue, minValue;
  
// Utility function to create 
// a new node 
static Node newNode(int key) 
    Node temp = new Node(); 
    temp.key = key; 
    temp.left = temp.right = null
    return (temp); 
  
// Function to calculate the 
// height of the tree 
static int findHeight(Node node) 
    // Base condition 
    if (node == null
        return 0
    int leftHeight = findHeight(node.left); 
    int rightHeight = findHeight(node.right); 
  
    // Return the maximum of the height 
    // of the left and right subtree 
    return 1 + (leftHeight > rightHeight 
                    ? leftHeight 
                    : rightHeight); 
  
// Function to find the width of the tree 
static void findWidth(Node node, int hd) 
    // Base cases 
    if (node == null
        return
  
    if (hd > maxValue) { 
        maxValue = hd; 
    
  
    if (hd < minValue) { 
        minValue = hd; 
    
  
    // Recursively call the function twice to find 
    // the maximum width 
    findWidth(node.left, hd - 1); 
    findWidth(node.right, hd + 1); 
  
// Function to traverse the tree and 
// store level order traversal in a matrix 
static void BFS(int [][]mtrx, Node node) 
    // Create queue for storing 
    // the addresses of nodes 
    Queue<Node> qu = new LinkedList<Node>(); 
  
    qu.add(node); 
  
    int i = -1, j = -1
  
    Node poped_node = null
  
    // Iterating over the queue to perform 
    // breadth-first search traversal 
    while (!qu.isEmpty()) { 
  
        i++; 
  
        int qsize = qu.size(); 
  
        while (qsize-- > 0) { 
            j++; 
  
            poped_node = qu.peek(); 
  
            // Store the data of the node into 
            // the matrix 
            mtrx[i][j] = poped_node.key; 
            qu.remove(); 
  
            // Performing BFS for the remaining 
            // nodes in the queue 
            if (poped_node.left != null) { 
                qu.add(poped_node.left); 
            
  
            if (poped_node.right != null) { 
                qu.add(poped_node.right); 
            
        
  
        j = -1
    
  
// Function for Middle to Up Down 
// Traversal of Binary Tree 
static void traverse_matrix(int [][]mtrx, int height, 
                    int width) 
    // Variables to handle rows and columns 
    // of the matrix 
    int up = (height / 2); 
    int down = up + 1
  
    boolean flag = true
    int k = 0
  
    // Print the middle row 
    for (int j = 0; j < width; j++) { 
        if (mtrx[up][j] != Integer.MAX_VALUE) { 
            System.out.print(mtrx[up][j]+ ", "); 
        
    
    System.out.println(); 
    up--; 
  
    // Loop to print the remaining rows 
    for (int i = 0; i < (height - 1); i++) { 
  
        // Condition to manage up and 
        // down indices in the matrix 
        if (flag) { 
            k = up; 
            up--; 
            flag = !flag; 
        
  
        else
            k = down; 
            down++; 
            flag = !flag; 
        
  
        // Loop to print the value 
        // of matrix cells in perticular row 
        for (int j = 0; j < width; j++) { 
  
            if (mtrx[k][j] != Integer.MAX_VALUE) { 
                System.out.print(mtrx[k][j]+ ", "); 
            
        
        System.out.println(); 
    
  
// A utility function for middle to 
// up down traversal 
static void printPattern(Node node) 
    // max, min has been taken for 
    // calculating the width of tree 
    maxValue = Integer.MIN_VALUE; 
    minValue = Integer.MAX_VALUE; 
    int hd = 0
  
    // Calculate the width of a tree 
    findWidth(node, hd); 
    int width = maxValue + Math.abs(minValue); 
  
    // Calculate the height of the tree 
    int height = findHeight(node); 
      
    // Double pointer to create 2D array 
    int [][]mtrx = new int[width][height]; 
  
    // Initialize complete matrix with 
    // MAX INTEGER(purpose garbage) 
    for (int i = 0; i < height; i++) { 
        for (int j = 0; j < width; j++) { 
            mtrx[i][j] = Integer.MAX_VALUE; 
        
    
  
    // Store the BFS traversal of the tree 
    // into the 2-D matrix 
    BFS(mtrx, node); 
  
    // Print the circular clockwise spiral 
    // traversal of the tree 
    traverse_matrix(mtrx, height, width); 
  
    // release extra memory 
    // allocated for matrix 
    mtrx =null
  
// Driver Code 
public static void main(String[] args) 
    /* 
                10 
            / \ 
            12 13 
            / \ 
            14 15 
            / \ / \ 
            21 22 23 24 
    */
  
    // Creating the above tree 
    Node root = newNode(10); 
    root.left = newNode(12); 
    root.right = newNode(13); 
  
    root.right.left = newNode(14); 
    root.right.right = newNode(15); 
  
    root.right.left.left = newNode(21); 
    root.right.left.right = newNode(22); 
    root.right.right.left = newNode(23); 
    root.right.right.right = newNode(24); 
  
    printPattern(root); 
  
// This code is contributed by Rajput-Ji

chevron_right


Output:

14, 15, 
12, 13, 
21, 22, 23, 24, 
10,

Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.




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