美文网首页
[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

    原题是: Given two non-empty binary trees s and t, check whet...

  • [easy+][Tree] 101.Symmetric Tree

    原题是: 思路是: 将给定的整颗树,进行复制。对复制的树,进行左右翻转操作,再对比翻转好的树,和原先的树是否是一样...

  • [easy+][Tree]543.

    原题是: Given a binary tree, you need to compute the length ...

  • [easy+][Tree] 563.Binary Tree Ti

    原题是: 思路是: 我一开始的思路是:第一步,写两个函数,第一个函数对一个给定的root,求以它为root的这棵树...

  • [easy+][Tree]110.Balanced Binary

    原题是: 思路是: 这个题与前面所刷的树的递归问题的一点区别在于:当前节点要判断是否平衡,除了需要知道它的左右子节...

  • [easy+][Tree][review]257.Binary

    原题是: 思路是: 这个题前面所有题的不同之处在于,从上到下的过程中,需要上一层的值,所以把上一层的值作为参数传入...

  • [easy+][Tree]112. Path Sum

    path sum 有好几题,是一个系列。 原题是: Given a binary tree and a sum, ...

  • transferable

    transferable :able to be transferred or made over to anot...

  • 数组练习

    Ransom NoteGiven an arbitrary ransom note string and anot...

  • Andrew Watson: The 'most influen

    There are two murals of black footballers facing one anot...

网友评论

      本文标题:[easy+][Tree]572.Subtree of Anot

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