![]() |
VOOZH | about |
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:
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,
Below is the implementation of the above approach:
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.