美文网首页
[easy+][Tree]572.Subtree of Anot

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

作者: 小双2510 | 来源:发表于2017-11-09 22:20 被阅读0次

    原题是:

    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.

    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 Anot

          本文链接:https://www.haomeiwen.com/subject/zlxvmxtx.html