1 Star 0 Fork 332

[]~( ̄ ̄)~* / leetcode

forked from doocs / leetcode 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
README_EN.md 2.28 KB
一键复制 编辑 原始数据 按行查看 历史
yanglbme 提交于 2020-10-20 11:19 . docs: prettify code

04.10. Check SubTree

中文文档

Description

T1 and T2 are two very large binary trees, with T1 much bigger than T2. Create an algorithm to determine if T2 is a subtree of T1.

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.

Example1:


 Input: t1 = [1, 2, 3], t2 = [2]

 Output: true

Example2:


 Input: t1 = [1, null, 2, 4], t2 = [3, 2]

 Output: false

Note:

  1. The node numbers of both tree are in [0, 20000].

Solutions

Find the t2 node in t1 first, then use the depth-first search (DFS) algorithm to make sure that the subtree and the subtree of t2 are identical, otherwise return FALSE.

Python3

class Solution:
    def checkSubTree(self, t1: TreeNode, t2: TreeNode) -> bool:
        if t1 == None:
            return False
        if t2 == None:
            return True
        return self.dfs(t1,t2) or self.checkSubTree(t1.left,t2) or self.checkSubTree(t1.right,t2)

    def dfs(self, t1: TreeNode, t2: TreeNode) -> bool:
        if not t1 and t2 :
            return False
        if not t2 and not t1:
            return True
        if t1.val != t2.val:
            return False
        else:
            return self.dfs(t1.left,t2.left) and self.dfs(t1.right,t2.right)

Java

class Solution {
    public boolean checkSubTree(TreeNode t1, TreeNode t2) {
        if (t2 == null)
            return true;
        if (t1 == null)
            return false;
        return isSubTree(t1, t2) || checkSubTree(t1.left, t2) || checkSubTree(t1.right, t2);
    }

    public boolean isSubTree(TreeNode t1, TreeNode t2){
        if (t2 == null)
            return true;
        if (t1 == null)
            return false;
        if (t1.val != t2.val)
            return false;
        return isSubTree(t1.left,t2.left) && isSubTree(t1.right,t2.right);
    }
}

...

Java
1
https://gitee.com/keshuimao/leetcode.git
git@gitee.com:keshuimao/leetcode.git
keshuimao
leetcode
leetcode
main

搜索帮助