572. 另一棵树的子树

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:
        result1 = []
        result2 = []
        subval = self.traversal(subRoot, result1, None)
        rootval = self.traversal(root, result2, subval)
        return not rootval or (subval == rootval)

    def traversal(self, root, result, compare):
        if not root:
            return [None]
        else:
            
            leftval = self.traversal(root.left, result, compare)
            rightval = self.traversal(root.right, result, compare)
            if leftval == 0 or rightval == 0:
                return 0
            if compare and (leftval == compare or rightval == compare):
                return 0
            else:
                return [root.val] + leftval + rightval

还是递归好用

你可能感兴趣的:(python,开发语言)