SubTree

You have two every large binary trees: T1, with millions of nodes, and T2, with hundreds of nodes. Create an algorithm to decide if T2 is a subtree of T1

 Notice

A tree T2 is a subtree of T1 if there exists a node n in T1 such that the subtree of n is identical to T2. That is, if you cut off the tree at node n, the two trees would be identical.

这题思路很明显,先找T1中和T2头结点一样的结点,找到这个节点后,如果这个节点构成能的子树和T2一样,则T2是T1的subtree。

但是需要注意的是:树中结点的值可能有重复,所以找到一个之后,如果还不是subtree,需要继续寻找。这个非常重要!!

代码如下:

"""
Definition of TreeNode:
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None
"""
class Solution:
    # @param T1, T2: The roots of binary tree.
    # @return: True if T2 is a subtree of T1, or false.
    def isSubtree(self, T1, T2):
        result = False
        if not T2:
            return True
        if not T1 and T2:
            return False
        if T1.val == T2.val:
            result = self.isSameTree(T1, T2)
        if not result:
            result = self.isSubtree(T1.left, T2)
        if not result:
            result = self.isSubtree(T1.right, T2)
        return result 
        
    def isSameTree(self, T1, T2):
        if not T1 and not T2:
            return True
        if (not T1 and T2) or (T1 and not T2):
            return False
        if T1.val != T2.val:
            return False
        else:
            return self.isSameTree(T1.left, T2.left) and self.isSameTree(T1.right,T2.right)
            

 

 

posted on 2016-08-07 17:33  Sheryl Wang  阅读(145)  评论(0编辑  收藏  举报

导航