对称二叉树
给你一个二叉树的根节点 root , 检查它是否轴对称。
示例 1:
输入:root = [1,2,2,3,4,4,3]
输出:true
示例 2:
输入:root = [1,2,2,null,3,null,3]
输出:false
提示:
树中节点数目在范围 [1, 1000] 内
-100 <= Node.val <= 100
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: bool isSymmetric(TreeNode* root) { std::queue<TreeNode*> q; if(root == nullptr){ return true; } q.push(root->left); q.push(root->right); while(!q.empty()){ auto left = q.front(); q.pop(); auto right = q.front(); q.pop(); if(left == nullptr && right == nullptr){ continue; } if(left == nullptr || right == nullptr || left->val != right->val){ return false; } q.push(left->left); q.push(right->right); q.push(right->left); q.push(left->right); } return true; } }; 关键:不要去想怎么去取队列的头尾问题,转化为将头尾放在一起就变得简单容易了,对称的话需要左边取一个,右边取一个 标签:right,TreeNode,val,nullptr,算法,10.5,root,left From: https://www.cnblogs.com/minipython-wldx/p/17743155.html