Leetcode 572. Subtree of Another Tree

Posted 周洋的Blog

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 572. Subtree of Another Tree相关的知识,希望对你有一定的参考价值。

可以借用一下leetcode 100的函数.

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def isSubtree(self, s: TreeNode, t: TreeNode) -> bool:
        stack=[s]
        while stack:
            node=stack.pop()
            if self.isSameTree(node,t):
                return True
            if node.right:
                stack.append(node.right)
            if node.left:
                stack.append(node.left)
        return False

        
        
    def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
        if (not p) and (not q):
            return True
        elif (not p) or (not q):
            return False
        else:
            if p.val==q.val:
                return self.isSameTree(p.left,q.left) and self.isSameTree(p.right,q.right)
            else:
                return False
        

 

以上是关于Leetcode 572. Subtree of Another Tree的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 572: Subtree of Another Tree

Leetcode 572. Subtree of Another Tree

leetcode572. Subtree of Another Tree

[LeetCode] 572. Subtree of Another Tree

[Leetcode] Binary tree-- 572. Subtree of Another Tree

LeetCode 572. 另一个树的子树(Subtree of Another Tree) 40