[LeetCode]Same Tree

本文介绍了一种用于判断两棵二叉树是否全等的方法,详细解释了算法思路,并提供了相应的代码实现。

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

Given two binary trees, write a function to check if they are equal or not.

Two binary trees are considered equal if they are structurally identical and the nodes have the same value.

这道题是要判断两棵树是不是全等。全等的定义是:

不仅树的结构要完全相同,相同位置上的结点的值也要相同。

思路很容易想到,对二叉树的层次遍历做一点修改:

取队列结点,将它的左右孩子指针全部入队列,无论存在不存在。

  1. 定义两个队列,分别存放两个树的结点
  2. 将两个树的根节点同时入队列
  3. 在队列不为空的前提下执行下列操作:
    1. 同时取队头结点,若都是空指针,则同时将其移除队列
    2. 若只有一个是空指针,则两个树不同,返回false
    3. 否则比较两个结点的元素值是否相等,若不等,则返回false
    4. 将队头结点的左右孩子指针全部分别入队列
  4. 最后若两个队列都为空,则两个树相同,否则不同。

下面贴上代码:

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isSameTree(TreeNode *p, TreeNode *q) {
        queue<TreeNode*> p1;
        queue<TreeNode*> p2;
        p1.push(p);
        p2.push(q);
        TreeNode* t1;
        TreeNode* t2;
        while (!p1.empty()&&!p2.empty()){
            t1 = p1.front();
            t2 = p2.front();
            if (t1&&t2){
                if (t1->val != t2->val)
                    return false;
            }
            else if((t1&&!t2)||(!t1&&t2)){
                return false;
            }
            else{
                p1.pop();
                p2.pop();
                continue;
            }
            p1.pop();
            p2.pop();
            p1.push(t1->left);
            p1.push(t1->right);
            p2.push(t2->left);
            p2.push(t2->right);
        }
        if (p1.empty() && p2.empty())
            return true;
        else
            return false;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值