zoukankan      html  css  js  c++  java
  • 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)
                
  • 相关阅读:
    leetcode44:wildcard
    Python实现决策树
    PCA实现
    js触摸事件
    js中的getBoundingClientRect()函数
    Java中timer的schedule()和schedualAtFixedRate()函数的区别
    nodejs中的exports和module.exports
    为什么MySQL数据库要用B+树存储索引
    浅谈微服务中的熔断,限流,降级
    缓存击穿、缓存穿透和缓存雪崩
  • 原文地址:https://www.cnblogs.com/sherylwang/p/5746711.html
Copyright © 2011-2022 走看看