📌  相关文章
📜  通过将每个节点替换为前一个级别的最小值的最近幂来修改二叉树

📅  最后修改于: 2021-04-17 15:58:49             🧑  作者: Mango

给定一个由N个节点组成的二叉树,任务是在将每个节点的值替换为原始树中上一级别的最小值的最接近幂后,打印级别顺序遍历。
注意:对于两个最接近的幂,请在其中选择最大值。

例子:

方法:想法是使用队列执行级别顺序遍历以解决问题。
请按照以下步骤解决问题:

  • 定义一个函数,例如mostestPow(X,Y),以找到整数Y的最接近的幂:
    • 查找基于Y的log(X)并将其存储在变量中,例如K。
    • 如果abs(X-Y K )小于abs(Y (K + 1) -X),则返回Y K。否则,返回Y (K +1)
  • 初始化两个变量,例如minCurrminPrev,以分别存储当前级别的最小值和先前级别的最小值。
  • 最初分配minPrev = root.val并初始化一个队列,例如Q,以存储要进行层级顺序遍历的节点。
  • Q不为空的情况下进行迭代():
    • 将队列的第一个节点存储在变量temp中,然后从队列Q中删除第一个节点。
    • minCurr的值分配给minPrev并更新minCurr = 10 18
    • [0,length(Q)– 1]范围内进行迭代,并将minCurr更新为minCurr = min(minCurr,temp.val) ,并将整数minPrev的最接近幂指定给temp.val
    • 在上述步骤的每次迭代中,如果各自的节点不为NULL则将temp.lefttemp.right推入。
  • 完成上述步骤后,打印经过更新的树的级别顺序遍历。

下面是上述方法的实现:

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)


输出:
7 7 7 16

时间复杂度: O(N)
辅助空间: O(N)