LeetCode Identical Binary Tree 相同二叉树

本文介绍了一种用于检查两棵二叉树是否完全相同的方法,包括它们的结构和每个对应节点的值。提供了两种解决方案:一种是递归方法,另一种是使用栈的迭代方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述:

Check if two binary trees are identical. Identical means the two binary trees have the same structure and every identical position has the same value.

样例输入:

    1             1
   / \           / \
  2   2   and   2   2
 /             /
4             4
    1             1
   / \           / \
  2   3   and   2   3
 /               \
4                 4

样例输出:

true
false

解法一:

有树的地方就有递归

private boolean isIdenticalRecursion(TreeNode a, TreeNode b) {
   if (a == null && b == null) {
        return true;
    }
    if ((a == null && b != null) || (a != null && b == null) || (a.val != b.val)) {
        return false;
    }
    return isIdenticalRecursion(a.left, b.left) && isIdenticalRecursion(a.right, b.right);
}

解法二:

递归能实现的循环也能实现

private boolean isIdenticalPreOrder(TreeNode a, TreeNode b) {
     Stack<TreeNode> stack1 = new Stack<>();
     Stack<TreeNode> stack2 = new Stack<>();
     stack1.push(a);
     stack2.push(b);
     while (!stack1.empty() && !stack2.empty()) {
         TreeNode tmp1 = stack1.pop();
         TreeNode tmp2 = stack2.pop();
         if (tmp1.val!=tmp2.val){
             return false;
         }
         if (tmp1.right!=null){
             stack1.push(tmp1.right);
         }
         if (tmp2.right!=null){
             stack2.push(tmp2.right);
         }
         if (stack1.size()!=stack2.size()){
             return false;
         }
         if (tmp1.left!=null){
             stack1.push(tmp1.left);
         }
         if (tmp2.left!=null){
             stack2.push(tmp2.left);
         }
         if (stack1.size()!=stack2.size()){
             return false;
         }
     }
     return stack1.size() == stack2.size();
 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值