Skip to content
Related Articles

Related Articles

Modify Binary Tree by replacing each node with nearest power of minimum of previous level

Improve Article
Save Article
Like Article
  • Last Updated : 25 Mar, 2022

Given a Binary Tree consisting of N nodes, the task is to print the Level Order Traversal after replacing the value of each node with its nearest power of the minimum value of the previous level in the original tree.
Note: For any case of two nearest powers, select the maximum among them.

Examples:

Input:    7
            /  \
         4   11
       /
   23
Output: 7 4 11 23 N
Explanation:

  • Node value at level 0 remains unchanged, i.e. 7.
  • Power of 7 nearest to 4 is 71 = 7.
    Power of 7 nearest to 11 is 71 = 7.
    Therefore, nodes at level 1 becomes {7, 7}.
  • Minimum node value at level 1 is 4.
    Power of 4 nearest to 23 is 44 = 16.
    Therefore, node at level 2 becomes {16}.

The resultant tree after completing the above operations is as follows:
              7
            /  \
         4   11
       /
   23

Input:   3
            / \
          2    6
       /   \    \
    45  71  25  
Output: 3 3 9 32 64 N 32

Approach: The idea is to perform the Level Order Traversal using a Queue to solve the problem. 
Follow the steps below to solve the problem:

  • Define a function, say nearestPow(X, Y), to find the nearest power of an integer Y:
    • Find log(X) base Y and store it in a variable, say K.
    • Return YK if abs(X – YK) is less than abs(Y(K + 1) – X). Otherwise, return Y(K + 1).
  • Initialize two variables, say minCurr and minPrev, to store the minimum value of the current level and the minimum value of the previous level respectively.
  • Initially assign minPrev = root.val and initialize a queue, say Q to store the nodes for level order traversal.
  • Iterate while Q is not empty():
    • Store the first node of the queue in a variable, say temp, and delete the first node from queue Q.
    • Assign the value of minCurr to minPrev and update minCurr = 1018.
    • Iterate over the range [0, length(Q) – 1] and update the minCurr as minCurr = min(minCurr, temp.val) and assign the nearest power of the integer minPrev to temp.val.
    • In each iteration of the above step push the temp.left and temp.right if the respective nodes are not NULL.
  • After completing the above steps, print the level order traversal of the updated Tree.

Below is the implementation of the above approach:

Python3




# Python program for the above approach
import math
 
# Structure of a Node of a Tree
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right
 
 
# Function to calculate the
# nearest power of an integer
def nearestPow(x, base):
    k = int(math.log(x, base))
     
    if abs(base**k - x) < abs(base**(k+1) - x):
        return base**k
    else:
        return base**(k+1)
 
# Iterative method to perform
# Level Order Traversal
def printLevelOrder(root):
 
    # Base Case
    if root is None:
        return
 
    # Queue for Level
    # Order Traversal
    q = []
 
    # Enqueue root
    q.append(root)
 
    while q:
 
        # Stores number of
        # nodes at current level
        count = len(q)
 
        # Dequeue all nodes of the current
        # level and Enqueue all nodes of
        # the next level
        while count > 0:
            temp = q.pop(0)
            print(temp.val, end=' ')
 
            # Push the left subtree
            # if not empty
            if temp.left:
                q.append(temp.left)
 
            # Push the right subtree
            # if not empty
            if temp.right:
                q.append(temp.right)
 
            # Decrement count by 1
            count -= 1
 
 
# Function to replace each node
# with nearest power of minimum
# value of previous level
def replaceNodes(root):
 
    # Stores the nodes of tree to
    # traverse in level order
    que = [root]
 
    # Stores current level
    lvl = 1
 
    # Stores the minimum
    # value of previous level
    minPrev = root.val
 
    # Stores the minimum
    # value of current level
    minCurr = root.val
 
    # Iterate while True
    while True:
 
        # Stores length of queue
        length = len(que)
 
        # If length is zero
        if not length:
            break
 
        # Assign minPrev = minCurr
        minPrev = minCurr
        minCurr = 1000000000000000000
 
        # Iterate over range [0, length - 1]
        while length:
 
            # Stores current node of tree
            temp = que.pop(0)
 
            # Update minCurr
            minCurr = min(temp.val, minCurr)
 
            # Replace current node with
            # nearest power of minPrev
            temp.val = nearestPow(temp.val, minPrev)
 
            # Left child is not Null
            if temp.left:
 
                # Append temp.left node
                # in the queue
                que.append(temp.left)
 
            # If right child is not Null
            if temp.right:
 
                # Append temp.right node
                # in the queue
                que.append(temp.right)
 
            # Decrement length by one
            length -= 1
 
        # Increment level by one
        lvl += 1
 
    # Function Call to perform the
    # Level Order Traversal
    printLevelOrder(root)
 
 
# Driver Code
 
# Given Tree
root = TreeNode(7)
root.left = TreeNode(4)
root.right = TreeNode(11)
root.left.right = TreeNode(23)
 
replaceNodes(root)

Javascript




<script>
 
// JavaScript program for the above approach
 
// Structure of a Node of a Tree
class TreeNode{
    constructor(val = 0, left = null, right = null){
        this.val = val
        this.left = left
        this.right = right
    }
}
 
// Function to calculate the
// nearest power of an integer
function nearestPow(x, base){
    let k = Math.floor(Math.log(x)/ Math.log(base))
    if(Math.abs(Math.pow(base,k) - x) < Math.abs(Math.pow(base,k+1) - x))
        return Math.pow(base,k)
    else
        return Math.pow(base,k+1)
}
 
// Iterative method to perform
// Level Order Traversal
function printLevelOrder(root){
 
    // Base Case
    if(root == null)
        return
 
    // Queue for Level
    // Order Traversal
    let q = []
 
    // Enqueue root
    q.push(root)
 
    while(q){
 
        // Stores number of
        // nodes at current level
        let count = q.length
 
        // Dequeue all nodes of the current
        // level and Enqueue all nodes of
        // the next level
        while(count > 0){
            let temp = q.shift()
            document.write(temp.val,' ')
 
            // Push the left subtree
            // if not empty
            if(temp.left)
                q.push(temp.left)
 
            // Push the right subtree
            // if not empty
            if(temp.right)
                q.push(temp.right)
 
            // Decrement count by 1
            count -= 1
        }
    }
}
 
// Function to replace each node
// with nearest power of minimum
// value of previous level
function replaceNodes(root){
 
    // Stores the nodes of tree to
    // traverse in level order
    let que = [root]
 
    // Stores current level
    let lvl = 1
 
    // Stores the minimum
    // value of previous level
    let minPrev = root.val
 
    // Stores the minimum
    // value of current level
    let minCurr = root.val
 
    // Iterate while True
    while(true){
 
        // Stores length of queue
        let Length = que.length
 
        // If length is zero
        if(!Length)
            break
 
        // Assign minPrev = minCurr
        minPrev = minCurr
        minCurr = 1000000000000000000
 
        // Iterate over range [0, length - 1]
        while(Length){
 
            // Stores current node of tree
            let temp = que.shift()
 
            // Update minCurr
            minCurr = Math.min(temp.val, minCurr)
 
            // Replace current node with
            // nearest power of minPrev
            temp.val = nearestPow(temp.val, minPrev)
 
            // Left child is not Null
            if(temp.left)
 
                // Append temp.left node
                // in the queue
                que.push(temp.left)
 
            // If right child is not Null
            if(temp.right)
 
                // Append temp.right node
                // in the queue
                que.push(temp.right)
 
            // Decrement length by one
            Length--
        }
        // Increment level by one
        lvl++
    }
 
    // Function Call to perform the
    // Level Order Traversal
    printLevelOrder(root)
}
 
// Driver Code
 
// Given Tree
let root = new TreeNode(7)
root.left = new TreeNode(4)
root.right = new TreeNode(11)
root.left.right = new TreeNode(23)
 
replaceNodes(root)
 
// This code is contributed by shinjanpatra
</script>
Output:
7 7 7 16

Time Complexity: O(N)
Auxiliary Space: O(N)


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!