leetcode- Symmetric Tree

本文介绍了一种使用队列进行宽度优先遍历的方法,以判断二叉树是否为镜像对称。通过记录节点的位置信息,确保了对称性的准确判断。

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

Question:

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example, this binary tree [1,2,2,3,4,4,3] is symmetric:

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

But the following [1,2,2,null,3,null,3] is not:

    1
   / \
  2   2
   \   \
   3    3

Solution:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 * 使用队列,宽度优先遍历。定义结构体MP,来记录节点的唯一位置
 */
class Solution {
public:
    typedef struct MP{
        TreeNode* node;//节点
        pair<int,int> f;//父节点和当前节点
        int d;//左孩子还是右孩子标志,对于根节点的左孩子的子孙几点,0代表左,1代表右;根节点的右孩子的子孙节点与根的左孩子相反
        MP(TreeNode* n , pair<int,int> p,int dd):node(n),f(p),d(dd){}
    }MP;
    bool isSymmetric(TreeNode* root) {
        if(!root || !root->left&&!root->right){
            return true;
        }
        vector<MP*> p1;
        vector<MP*> p2;
        //根节点左右孩子入队列
        if(root->left){
            p1.push_back(new MP(root->left,make_pair(root->val,root->left->val),0));
        }
        if(root->right){
            p2.push_back(new MP(root->right,make_pair(root->val,root->right->val),0));
        }
        //左右孩子按广度优先入队列
        for(int i = 0 ; i<p1.size();i++){
            if(p1[i]->node->left){
                p1.push_back(new MP(p1[i]->node->left,make_pair(p1[i]->node->val,p1[i]->node->left->val),0));
            }
            if(p1[i]->node->right){
                p1.push_back(new MP(p1[i]->node->right,make_pair(p1[i]->node->val,p1[i]->node->right->val),1));
            }
        }
        for(int i = 0 ; i<p2.size();i++){
            if(p2[i]->node->right){
                p2.push_back(new MP(p2[i]->node->right,make_pair(p2[i]->node->val,p2[i]->node->right->val),0));
            }
            if(p2[i]->node->left){
                p2.push_back(new MP(p2[i]->node->left,make_pair(p2[i]->node->val,p2[i]->node->left->val),1));
            }
        }
        //检测两个队列是否相等
        int len;
        if((len=p1.size())!=p2.size()){
            return false;
        }
        for(int i = 0;i<len;i++){
            if(p1[i]->f == p2[i]->f && p1[i]->d == p2[i]->d){
                continue;
            }
            else{
                return false; 
            }
        } 
        return true;
    }
};

总结:

父节点是必须要给出的,比如
用例:2,3,3,4,5,5,4,null,null,8,9,null,null,9,8.
如果不给出父节点,结果出错。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值