VOOZH about

URL: https://www.geeksforgeeks.org/dsa/middle-to-up-down-order-traversal-of-a-binary-tree/

⇱ Middle To Up-Down Order traversal of a Binary Tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Middle To Up-Down Order traversal of a Binary Tree

Last Updated : 12 Jul, 2025

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, the 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 ree 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: 
     

👁 Image

  • 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: 


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

 

The time complexity of the findHeight function is O(V), as it visits each node in the tree exactly once and performs a constant amount of work for each node. The time complexity of the findWidth function is also O(V), as it similarly visits each node in the tree exactly once

The Auxiliary Space of this implementation is O(V), where V is the number of nodes in the tree. This is because the BFS function uses a queue to store the addresses of the nodes during the traversal, and the size of the queue is at most equal to the number of nodes in the tree.

Comment