[easy+][Tree]572.Subtree of Another Tree

原题是:

Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node's descendants. The tree s could also be considered as a subtree of itself.

[easy+][Tree]572.Subtree of Another Tree_第1张图片
Screen Shot 2017-11-09 at 9.18.11 AM.png

思路是:

之前刷过一道题,叫做sameTree,就是比较两个树是否完全相同。这个可以应用到本题中来,只需逐个比较s中的每个节点为Root的树和t是否互为相同树。

代码是:

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

class Solution(object):
    def isSubtree(self, s, t):
        """
        :type s: TreeNode
        :type t: TreeNode
        :rtype: bool
        """
        if s == None:
            return False
        elif self.sameTree(s,t):
            return True
        elif self.isSubtree(s.left,t):
            return True
        elif self.isSubtree(s.right,t):
            return True
        
        return False
                
                
    def sameTree(self,root1,root2):
        if not (root1 or root2):
            return True
        elif not(root1 and root2):
            return False
        elif root1.val == root2.val:
            Left = self.sameTree(root1.left,root2.left)
            Right = self.sameTree(root1.right,root2.right)
            if Left and Right:
                return True
        return False

你可能感兴趣的:([easy+][Tree]572.Subtree of Another Tree)