牛客题目链接
1. 题目考点
- 仔细审题,
是完全拓扑结构
,不是部分
1 和 1 就不是 t1 完全包含 t2,而是部分包含 t2
/ \ /
2 3 2
- 两次 dfs
- 如何递归判断两个二叉树是否相等
- 将 # 特殊处理成 0,补全二叉树为完全二叉树
2. 考点解析
- 两次 dfs,
外层 dfs 看做对 t1 的 for 循环,遍历 t1 的每个节点
- 递归判断两个二叉树是否相等,本质上是判断
两个节点是否相等
,然后对节点子树递归判断
public boolean isContains (TreeNode root1, TreeNode root2) {
if (root1 == null) return false;
boolean b1 = bfs(root1, root2);
return b1 || isContains(root1.left, root2) || isContains(root1.right, root2);
}
public boolean bfs(TreeNode root1, TreeNode root2) {
if (root1 == null && root2 == null) return true;
if (root1 == null || root2 == null || root1.val != root2.val) return false;
return bfs(root1.left, root2.left) && bfs(root1.right, root2.right);
}
- 补全 #,
求 t1 和 t2 的先序序列
,保存至 StringBuffer 的 res1 res2,判断 res1 是否 contains res2
public boolean isContains (TreeNode root1, TreeNode root2) {
StringBuffer res1 = new StringBuffer();
StringBuffer res2 = new StringBuffer();
dfs(root1, res1);
dfs(root2, res2);
if (res1.toString().contains(res2.toString())) return true;
return false;
}
public void dfs(TreeNode root, StringBuffer res) {
if (root == null) {
res.append(0);
return ;
}
res.append(root.val);
dfs(root.left, res);
dfs(root.right, res);
}