Leetcode 100. 相同的树

题目

给定两个二叉树,编写一个函数来检验它们是否相同。

如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。

在这里插入图片描述在这里插入图片描述在这里插入图片描述

解答

解法一:递归

递归很好理解。

先比较当前结点,如果当前结点相等,再比较左右子树是否相等。

代码
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if(p == null) return q == null;
        if(q == null) return p == null;
        return p.val == q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
    }
}
结果

在这里插入图片描述

解法二:队列 + 迭代

使用队列,将两棵树相同位置的结点放在一个 Couple 中。

如果 Couple 比对不相等,直接返回 false。

否则如果当前结点不为 null,就把新的左右结点加入队列。

代码
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    class Couple {
        TreeNode n1;
        TreeNode n2;
        
        Couple(TreeNode n1, TreeNode n2) {
            this.n1 = n1;
            this.n2 = n2;
        }
    }
    
    public boolean isSameTree(TreeNode p, TreeNode q) {
        LinkedList<Couple> queue = new LinkedList<>();
        queue.offer(new Couple(p, q));
        while(!queue.isEmpty()) {
            Couple top = queue.poll();
            TreeNode n1 = top.n1;
            TreeNode n2 = top.n2;
            if(!equals(n1, n2)) return false;
            
            if(n1 != null && n2 != null) {
                queue.offer(new Couple(n1.left, n2.left));
                queue.offer(new Couple(n1.right, n2.right));
            }
        }
        
        return true;
    }
    
    public boolean equals(TreeNode p, TreeNode q) {
        if(p == null) return q == null;
        if(q == null) return p == null;
        return p.val == q.val;
    }
}
结果

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值