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
        

 

posted @ 2019-04-23 04:40  周洋  阅读(230)  评论(0编辑  收藏  举报