好久没刷题今天有时间挑选了这道Symmetric Tree(对称二叉树)。
按照最直观的思路层序遍历,然后判断每一层是否对称。
/**
* 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) {
queue<TreeNode *> q;
if(root) q.push(root);
while(!q.empty())
{
int n = q.size();
vector<int> vec(n,0);
for(int i = 0;i < n;i++)
{
TreeNode* node = q.front();
q.pop();
vec[i] = node->val;
if(node->left)
q.push(node->left);
if(node->right)
q.push(node->right);
}
if(!judgeSymmetric(vec)) return false;
}
return true;
}
private:
bool judgeSymmetric(const vector<int>& vec)
{
int n = vec.size();
for(int i = 0;i < n / 2;i++)
{
if(vec[i] != vec[n-1-i]) return false;
}
return true;
}
};
最后发现有一种case无法处理,形如[1,2,2,null,3,null,3]等等情况。
正确的解法是使用层序遍历的变种:
/**
* 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) {
return isSymmetric(root,root);
}
private:
bool isSymmetric(TreeNode* left,TreeNode* right) {
queue<TreeNode*> q;
q.push(left),q.push(right);
while(!q.empty())
{
TreeNode* u = q.front();q.pop();
TreeNode* v = q.front();q.pop();
//都是空指针,继续处理
if(!u && !v) continue;
//1.其中一个指针为空 或 值不相等返回false
if((!u || !v) || u->val != v->val) return false;
//插入顺序:left:从左向右,right:从右向左
q.push(u->left);q.push(v->right);
q.push(u->right);q.push(v->left);
}
return true;
}
};
递归实现:
/**
* 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) {
return isSymmetric(root,root);
}
private:
bool isSymmetric(TreeNode* p,TreeNode* q) {
if(!p && !q) return true;
if(!p || !q) return false;
return (p->val == q->val) && isSymmetric(p->left,q->right) && isSymmetric(p->right,q->left);
}
};