Python程序:检查一棵树是否为另一棵树的子树
假设我们有两棵二叉树。我们需要检查第二棵树是否为第一棵树的子树。
例如,输入:
则输出为True。
为了解决这个问题,我们将遵循以下步骤:
定义一个函数solve()。它将接收根节点和目标节点作为参数。
如果根节点和目标节点都为空,则
返回True
如果根节点为空或目标节点为空,则
返回False
如果根节点的值与目标节点的值相同,则
返回 solve(根节点的左子树, 目标节点的左子树) 并且 solve(根节点的右子树, 目标节点的右子树)
否则,
返回 solve(根节点的左子树, 目标节点) 或 solve(根节点的右子树, 目标节点)
让我们来看下面的实现,以便更好地理解:
示例
class TreeNode: def __init__(self, data, left = None, right = None): self.val = data self.left = left self.right = right class Solution: def solve(self, root, target): if root == None and target == None: return True if root == None or target == None: return False if root.val == target.val: return self.solve(root.left, target.left) and self.solve(root.right, target.right) else: return self.solve(root.left, target) or self.solve(root.right, target) ob = Solution() root1 = TreeNode(6) root1.left = TreeNode(4) root1.right = TreeNode(10) root1.left.left = TreeNode(3) root1.left.right = TreeNode(5) root2 = TreeNode(4) root2.left = TreeNode(3) root2.right = TreeNode(5) print(ob.solve(root1, root2))
输入
root1 = TreeNode(6) root1.left = TreeNode(4) root1.right = TreeNode(10) root1.left.left = TreeNode(3) root1.left.right = TreeNode(5) root2 = TreeNode(4) root2.left = TreeNode(3) root2.right = TreeNode(5)
输出
True
广告