[LeetCode] 04.10 检查子树

检查子树

描述

有两棵非常大的二叉树:T1,有几万个节点;T2,有几万个节点。
设计一个算法,判断 T2 是否为 T1 的子树。
如果 T1 有一个节点 n,其子树与 T2 一模一样,则 T2 为 T1 的子树
也就是说,从节点 n 处把树砍断,得到的树与 T2 完全相同。

样例

输入:t1 = [1, 2, 3], t2 = [2]
输出:true

原题链接

思路

[LeetCode] 04.10 检查子树_第1张图片
递归:从t1的每个节点开始对比,判断是否与t2树相同。

设计一个dfs递归函数,用以判断t1、t2的子树的结构是否相同。
当前两个节点不相同,则向t1的左孩子和右孩子继续判断。
[LeetCode] 04.10 检查子树_第2张图片
当前两节点的值相等,才能继续向下递归判别

[LeetCode] 04.10 检查子树_第3张图片

代码

public class Main {
    public static boolean checkSubTree(TreeNode t1, TreeNode t2) {
        if (t1==null){
            return false;
        }
        if (t2==null){
            return true;
        }
		//因为不一定是从根节点开始,两棵树一模一样
		//也可能是从t1的某个节点开始,两棵树完全相同了
        return dfs(t1,t2)
                || checkSubTree(t1.left,t2)
                || checkSubTree(t1.right,t2);
    }

    private static boolean dfs(TreeNode t1, TreeNode t2) {
        if (t2==null){
            return true;
        }
        if (t1==null||t1.val!=t2.val){
            return false;
        }
        //此时t1节点和t2节点值相同,再继续判断二者的子树是否相同
        return dfs(t1.left,t2.left)  || dfs(t1.right,t2.right);
    }
}

类似题目

树的子结构

你可能感兴趣的:(Java习题)