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.
Examples:
Input: 5
/ \
3 2
/ \
16 19Output: 9
/ \
4 4
/ \
9 25Explanation:
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.
Input: 45
/ \
65 32
/
89Output: 49
/ \
64 36
/
81Explanation:
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:
- If the value of level is odd, and the value of the current node is even, find the nearest odd perfect square and update temp_node→data.
- If the value of level is even and the value of the current node is odd, find the nearest even perfect square and update temp_node→data.
- 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:
C++
// C++ program for the above approach#include <bits/stdc++.h>using namespace std;// Structure of a// Binary Tree Nodestruct Node { int data; struct Node *left, *right;};// Function to replace all nodes// at even and odd levels with their// nearest even or odd perfect squaresvoid LevelOrderTraversal(Node* root){ // Base Case if (root == NULL) return; // Create an empty queue // for level order traversal queue<Node*> q; // Enqueue root q.push(root); // Initialize height int lvl = 1; // Iterate until queue is not empty while (q.empty() == false) { // Store the size // of the queue int n = q.size(); // Traverse in range [1, n] for (int i = 0; i < n; i++) { // Store the current node Node* node = q.front(); // Store its square root double num = sqrt(node->data); int x1 = floor(num); int x2 = ceil(num); // Check if it is a perfect square if (x1 == x2) { // If level is odd and value is even, // find the closest odd perfect square if ((lvl & 1) && !(x1 & 1)) { int num1 = x1 - 1, num2 = x1 + 1; node->data = (abs(node->data - num1 * num1) < abs(node->data - num2 * num2)) ? (num1 * num1) : (num2 * num2); } // If level is even and value is odd, // find the closest even perfect square if (!(lvl & 1) && (x1 & 1)) { int num1 = x1 - 1, num2 = x1 + 1; node->data = (abs(node->data - num1 * num1) < abs(node->data - num2 * num2)) ? (num1 * num1) : (num2 * num2); } } // Otherwise, find the find // the nearest perfect sqaure else { if (lvl & 1) node->data = (x1 & 1) ? (x1 * x1) : (x2 * x2); else node->data = (x1 & 1) ? (x2 * x2) : (x1 * x1); } // Print front of queue // and remove it from queue cout << node->data << " "; q.pop(); // Enqueue left child if (node->left != NULL) q.push(node->left); // Enqueue right child if (node->right != NULL) q.push(node->right); } // Increment the level by 1 lvl++; cout << endl; }}// Utility function to// create a new tree nodeNode* newNode(int data){ Node* temp = new Node; temp->data = data; temp->left = temp->right = NULL; return temp;}// Driver Codeint main(){ // Binary Tree Node* root = newNode(5); root->left = newNode(3); root->right = newNode(2); root->right->left = newNode(16); root->right->right = newNode(19); LevelOrderTraversal(root); return 0;} |
Python3
# Python3 program for the above approachfrom collections import dequefrom math import sqrt, ceil, floor# Structure of a# Binary Tree Nodeclass Node: def __init__(self, x): self.data = x self.left = None self.right = None# Function to replace all nodes# at even and odd levels with their# nearest even or odd perfect squaresdef LevelOrderTraversal(root): # Base Case if (root == None): return # Create an empty queue # for level order traversal q = deque() # Enqueue root q.append(root) # Initialize height lvl = 1 # Iterate until queue is not empty while (len(q) > 0): # Store the size # of the queue n = len(q) # Traverse in range [1, n] for i in range(n): # Store the current node node = q.popleft() # Store its square root num = sqrt(node.data) x1 = floor(num) x2 = ceil(num) # Check if it is a perfect square if (x1 == x2): # If level is odd and value is even, # find the closest odd perfect square if ((lvl & 1) and not (x1 & 1)): num1, num2 = x1 - 1, x1 + 1 node.data = (num1 * num1) if (abs(node.data - num1 * num1) < abs(node.data - num2 * num2)) else (num2 * num2) # If level is even and value is odd, # find the closest even perfect square if (not (lvl & 1) and (x1 & 1)): num1,num2 = x1 - 1, x1 + 1 node.data = (num1 * num1) if (abs(node.data - num1 * num1) < abs(node.data - num2 * num2)) else (num2 * num2) # Otherwise, find the find # the nearest perfect sqaure else: if (lvl & 1): node.data = (x1 * x1) if (x1 & 1) else (x2 * x2) else: node.data = (x2 * x2) if (x1 & 1) else (x1 * x1) # Prfront of queue # and remove it from queue print(node.data, end = " ") # Enqueue left child if (node.left != None): q.append(node.left) # Enqueue right child if (node.right != None): q.append(node.right) # Increment the level by 1 lvl += 1 print()# Driver Codeif __name__ == '__main__': # Binary Tree root = Node(5) root.left = Node(3) root.right = Node(2) root.right.left = Node(16) root.right.right = Node(19) LevelOrderTraversal(root) # This code is contributed by mohit kumar 29. |
9 4 4 9 25
Time Complexity: O(N)
Auxiliary Space: O(N)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

