检查子树。你有两棵非常大的二叉树:T1,有几万个节点;T2,有几万个节点。设计一个算法,判断 T2 是否为 T1 的子树。
如果 T1 有这么一个节点 n,其子树与 T2 一模一样,则 T2 为 T1 的子树,也就是说,从节点 n 处把树砍断,得到的树与 T2 完全相同。
示例1:
输入:t1 = [1, 2, 3], t2 = [2]
输出:true
示例2:
输入:t1 = [1, null, 2, 4], t2 = [3, 2]
输出:false
提示:
树的节点数目范围为[0, 20000]。
思路:遍历二叉树t1的每一个节点,看能否找到以该节点为根的树与t2相同。
代码实现:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public static boolean isSame(TreeNode t1, TreeNode t2) {
//当同时到达叶子节点的后继(都为空),依然没返回false,就返回true
if (t1 == null && t2 == null) {
return true;
}
//待比较的两个节点一个为空,另一个不为空,说明这两棵树不相等
if (t1 == null || t2 == null) {
return false;
}
//如果待比较的两个节点都不为空,就比较它们的值是否相等,如果值相等就继续判断它们的左、右子树是否相等
return t1.val == t2.val && isSame(t1.left, t2.left) && isSame(t1.right, t2.right);
}
public boolean checkSubTree(TreeNode t1, TreeNode t2) {
//如果遍历到达的节点为空,则判断t2是否也为空,若是返回true,不是返回false
if (t1 == null) {
return t2 == null;
}
//遍历t1的每一个节点,看能否找到一棵子树与t2相同
return isSame(t1, t2) || (checkSubTree(t1.left, t2) || checkSubTree(t1.right, t2));
}
}