题目
检查子树。你有两棵非常大的二叉树:T1,有几万个节点;T2,有几万个节点。设计一个算法,判断 T2 是否为 T1 的子树。
如果 T1 有这么一个节点 n,其子树与 T2 一模一样,则 T2 为 T1 的子树,也就是说,从节点 n 处把树砍断,得到的树与 T2 完全相同。
示例1:
输入:t1 = [1, 2, 3], t2 = [2]
输出:true
解题思路
递归、DFS
- 递归判断两树节点是否相等
- 如果当前节点相等
- 比较两树左节点
- 比较两树右节点
- 如果当前节点不等
- t1.left与t2比较
- t1.right与t2比较
代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean checkSubTree(TreeNode t1, TreeNode t2) {
// t1、t2都为null,则t1、t2相等
if (t1 == null && t2 == null) return true;
// 否则,t1、t2不等
else if (t1 == null || t2 == null) return false;
// 当前节点不等,判断t2是否与t1.left或t1.right相同?
if (t1.val != t2.val) return checkSubTree(t1.left, t2) || checkSubTree(t1.right, t2);
// 否则继续比较t1.left、t2.left,t1.right、t2.right
return checkSubTree(t1.left, t2.left) && checkSubTree(t1.right, t2.right);
}
}