Python程序检查两棵树的叶子序列是否相同


假设我们有两棵二叉树,我们需要检查这两棵树中从左到右的叶子序列是否相同。

因此,如果输入类似于

则输出将为True,因为两棵树的序列都是[2, 6]。

为了解决这个问题,我们将遵循以下步骤

  • c := 一个新的列表
  • 定义一个函数inorder()。它将接收根节点和c作为参数。
  • 如果c为空,则
    • c := 一个新的列表
  • 如果根节点不为空,则
    • inorder(根节点的左子节点, c)
    • 如果根节点的左子节点和右子节点都为空,则
      • 将根节点的值插入到c的末尾
    • inorder(根节点的右子节点, c)
  • 返回c
  • 从主方法中执行以下操作
  • 如果inorder(root0)与inorder(root1)相同,则
    • 返回True
  • 否则,
    • 返回False

让我们查看以下实现以更好地理解

示例

在线演示

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

class Solution:
   c = []

   def inorder(self, root, c=None):
      if c is None:
         c = []
      if root:
         self.inorder(root.left, c)
         if not root.left and not root.right:
            c.append(root.val)
            self.inorder(root.right, c)
      return c

   def solve(self, root0, root1):
      if self.inorder(root0) == self.inorder(root1):
         return True
      else:
         return False

ob = Solution()
root1 = TreeNode(1)
root1.right = TreeNode(3)
root1.right.left = TreeNode(2)
root1.right.right = TreeNode(6)

root2 = TreeNode(1)
root2.left = TreeNode(3)
root2.right = TreeNode(6)
root2.left.left = TreeNode(2)
print(ob.solve(root1, root2))

输入

root1 = TreeNode(1)
root1.right = TreeNode(3)

root1.right.left = TreeNode(2)

root1.right.right = TreeNode(6) 

root2 = TreeNode(1)

root2.left = TreeNode(3)

root2.right = TreeNode(6)

root2.left.left = TreeNode(2)

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

输出

True

更新于: 2020年11月26日

83 次查看

开启你的职业生涯

通过完成课程获得认证

立即开始
广告