java 判断二叉树 t1 是否包含二叉树 t2 的完全拓扑结构

牛客题目链接

1. 题目考点

  1. 仔细审题,是完全拓扑结构,不是部分
	11      就不是 t1 完全包含 t2,而是部分包含 t2
  /   \             /
 2	   3           2
  1. 两次 dfs
  2. 如何递归判断两个二叉树是否相等
  3. 将 # 特殊处理成 0,补全二叉树为完全二叉树

2. 考点解析

  1. 两次 dfs,外层 dfs 看做对 t1 的 for 循环,遍历 t1 的每个节点
  2. 递归判断两个二叉树是否相等,本质上是判断两个节点是否相等,然后对节点子树递归判断
public boolean isContains (TreeNode root1, TreeNode root2) {
    // write code here
    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);
}
  1. 补全 #,求 t1 和 t2 的先序序列,保存至 StringBuffer 的 res1 res2,判断 res1 是否 contains res2
public boolean isContains (TreeNode root1, TreeNode root2) {
   // write code here
    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) {
    	// 把空节点补齐,当做 0 处理
        res.append(0);
        return ;
    }
    res.append(root.val);
    dfs(root.left, res);
    dfs(root.right, res);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值