39.判断对称二叉树

1.迭代法

分析:队列层序遍历,一次出队列两个,按左左 ,右右,左右,右左,的顺序入队

cpp 复制代码
bool idsyme(TreeNode* root){
     if(root==NULL) return true;
     queue<TreeNode*> q;
     q.push(root->left);
     q.push(root->right);
     while (!q.empty()) {
     TreeNode* leftnode = q.front();
     q.pop();
     TreeNode* rightnode = q.front();
     q.pop();
     if (leftnode == NULL && rightnode == NULL){
        continue;
     }
     if (leftnode==NULL || rightnode==NULL||(leftnode->val != rightnode->val))
     {
        return false;
     }
      
     q.push(leftnode->left);
     q.push(rightnode->right);
     q.push(leftnode->right);
     q.push(rightnode->left);
 }
 return true;


}

2.递归法

递归入口是两个节点,因此我们重新写一个函数进行递归,参数有两个节点,对根的左子树和右子树进行递归,画basecase的时候记得要画有两个节点可以进入递归的情况,如图

可以看到一些不对称的条件,如代码中的条件

cpp 复制代码
 bool isSymmetric(TreeNode* root) {

   if(root==NULL) return true;

   return fun(root->left,root->right);
}
bool fun(TreeNode* l,TreeNode* r){
    if(l==NULL && r==NULL) return true;
    if((l==NULL&&r!=NULL) || (l!=NULL && r==NULL)||l->val!=r->val){
        return false;
    }
    bool a = fun(l->left,r->right);
    bool b = fun(l->right,r->left);
    return a&&b;
}
};
相关推荐
m0_547486663 天前
《数据结构教程》全套 PPT课件2026
数据结构
tryxr3 天前
矩阵的几种基础变换
java·数据结构·算法·矩阵
mmmmath_33 天前
LeetCode.028.找出字符串中第一个匹配项的
数据结构·算法·leetcode
All for pursuit.3 天前
【栈-4】739.每日温度
数据结构·c++·算法·leetcode
All for pursuit.3 天前
【栈-5】84.柱状图中最大的矩形
数据结构·c++·算法·leetcode
渡我白衣3 天前
HttpRequest与HttpResponse的实现
服务器·数据结构·c++·人工智能·tcp/ip·机器学习·caffe
晴天的雨.9923 天前
【C++算法】和为s的两个数
开发语言·数据结构·c++·算法
淡海水4 天前
13-04-面试-源码级深度追问链
数据结构·unity·面试·c#·游戏引擎·源码·il2cpp
Logic1014 天前
C语言/数据结构位运算题解:异或XOR找出时尚聚会中的“独特颜色“——只出现一次的数字
c语言·数据结构·数组·位运算·时间复杂度·算法题·异或性质
2401_839080544 天前
C++常见八股
数据结构·c++·算法