【问题标题】:Merging two binary trees node sum合并两个二叉树节点和
【发布时间】:2020-01-18 13:28:30
【问题描述】:

我正在研究合并两个二叉树节点和 (https://www.geeksforgeeks.org/merge-two-binary-trees-node-sum/) 的问题,但我无法理解某些递归。为什么要将递归语句设置为t1.leftt1.right?当您这样做时,t1.left 是否等于两个值?

我只是不确定为什么我们要将递归语句设置为 t1.leftort1.right`

class newNode: 
def __init__(self, data): 
    self.data = data  
    self.left = self.right = None


def inorder(node): 
    if (not node): 
        return

inorder(node.left)  

print(node.data, end = " ")  

inorder(node.right) 


def MergeTrees(t1, t2): 
    if (not t1):  
        return t2  
    if (not t2): 
        return t1  
    t1.data += t2.data  
    t1.left = MergeTrees(t1.left, t2.left)  
    t1.right = MergeTrees(t1.right, t2.right)  
    return t1 

if __name__ == '__main__': 

# Let us construct the first Binary Tree  
#    1  
#    / \  
#    2   3  
# / \    \  
# 4 5    6  
root1 = newNode(1)  
root1.left = newNode(2)  
root1.right = newNode(3)  
root1.left.left = newNode(4)  
root1.left.right = newNode(5)  
root1.right.right = newNode(6)  

# Let us construct the second Binary Tree  
#    4  
#    / \  
# 1  7  
# /  / \  
# 3  2 6  
root2 = newNode(4)  
root2.left = newNode(1)  
root2.right = newNode(7)  
root2.left.left = newNode(3)  
root2.right.left = newNode(2)  
root2.right.right = newNode(6)  

root3 = MergeTrees(root1, root2)  
print("The Merged Binary Tree is:")  
inorder(root3) 

【问题讨论】:

    标签: algorithm recursion data-structures binary-tree


    【解决方案1】:

    要使用递归合并树,请遵循典型公式:

    1. 在当前节点上操作
    2. 对一个孩子进行手术
    3. 对另一个孩子进行手术

    在这种情况下,可以很方便地为其中一棵树就地完成合并。您合并当前的根节点。然后你在左孩子上递归,它将t2.left合并到t1.left;您将其分配给t1.left,以便合并的左子树干净地替换原来的。你对右子树做同样的事情。

    还清楚吗?

    【讨论】:

      【解决方案2】:

      在构造Node 时,首先可以设置leftright 分支-

      class Node:
        def __init__(self, data, left = None, right = None):
          self.data = data
          self.left = left
          self.right = right
      

      现在我们可以直接构造它们,而不是使用 node.left = ...node.right = ... 来变异树 -

      # Let us construct the first Binary Tree  
      #     1  
      #    / \  
      #   2   3  
      #  / \   \  
      # 4   5   6  
      
      t1 = Node(1, Node(2, Node(4), Node(5)), Node(3, None, Node(6)))
      

      在我们继续之前,让我们在 Node 上实现 __str__,这样我们就可以可视化这些树 -

      class Node:
        def __init__(...):
          # ...
      
        def __str__(self, pre="", child=""):
          if self is None:
            return "()"
          else:
            return f"({self.data} {self.left} {self.right})"
      
      print(t1)
      # (1 (2 (4 None None) (5 None None)) (3 None (6 None None)))
      

      现在让我们实现merge。能够在Node 构造函数中指定leftright 值使得编写它更容易-

      def merge(t1, t2):
        if t1 is None and t2 is None:
          return None
        elif t1 is None:
          return t2
        elif t2 is None:
          return t1
        else:
          return Node(t1.data + t2.data, merge(t1.left, t2.left), merge(t1.right, t2.right)
      
      print(merge(t1, t1))
      # (2 (4 (8 None None) (10 None None)) (6 None (12 None None)))
      

      现在我们可以看到+ 是如何轻松进行其他操作的。向merge 添加另一个参数可以使用任何操作进行合并 -

      def merge(f, t1, t2):
        if t1 is None and t2 is None:
          return None
        elif t1 is None:
          return t2
        elif t2 is None:
          return t1
        else:
          return Node(
            f(t1.data, t2.data),
            merge(f, t1.left, t2.left),
            merge(f, t1.right, t2.right)
          )
      
      print(merge(lambda a, b: a + b, t1, t1))
      # (2 (4 (8 None None) (10 None None)) (6 None (12 None None)))
      
      print(merge(lambda a, b: a * b, t1, t1))
      # (1 (4 (16 None None) (25 None None)) (9 None (36 None None)))
      

      或者使用operator模块-

      from operator import add, mul
      
      print(merge(add, t1, t1))
      # (2 (4 (8 None None) (10 None None)) (6 None (12 None None)))
      
      print(merge(mul, t1, t1))
      # (1 (4 (16 None None) (25 None None)) (9 None (36 None None)))
      

      【讨论】:

        猜你喜欢
        • 2019-11-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多