Modify Binary Tree by replacing all nodes at even and odd levels by their nearest even or odd perfect squares respectively
Given a Binary Tree consisting of N nodes, the task is to replace all the nodes that are present at even-numbered levels in a Binary Tree with their nearest even perfect square and replace nodes at odd-numbered levels with their nearest odd perfect square.
Level 1: Nearest odd perfect square to 5 is 9.
Level 2: Nearest even perfect square to 3 and 2 are 4.
Level 3: Nearest odd perfect square to 16 is 9 and to 19 is 25.
Level 1: Nearest odd perfect square to 45 is 49.
Level 2: Nearest even perfect square to 65 and 32 are 64 and 36 respectively.
Level 3: Nearest odd perfect square to 89 is 81.
Approach: The given problem can be solved using Level Order Traversal. Follow the steps below to solve the problem:
- Initialize a queue, say q.
- Push root into the queue.
- Loop while the queue is not empty
- Store the current node in a variable, say temp_node.
- If the current node value is a perfect square, check the following:
- Otherwise, find the nearest odd perfect square if the value of level is odd or the closest even perfect square if the value of level is even. Update temp_node→data.
- Print temp_node→data.
- Enqueue temp_node’s children (first left, then right child) to q, if exists.
- Dequeue current node from q.
Below is the implementation of the above approach:
9 4 4 9 25
Time Complexity: O(N)
Auxiliary Space: O(N)