101. 对称二叉树
给定一个二叉树,检查它是否是镜像对称的。
例如,二叉树 [1,2,2,3,4,4,3] 是对称的。
1
/ \
2 2
/ \ / \
3 4 4 3
但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:
1
/ \
2 2
\ \
3 3
递归法
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isSymmetric(TreeNode* root) {
if(root == NULL) return true;
return isBool(root,root);
}
bool isBool(TreeNode* Lroot,TreeNode* Rroot)
{
if(!Lroot && !Rroot) return true;
if(!Lroot || !Rroot) return false;
if(Lroot->val == Rroot->val)
{
return isBool(Lroot->left,Rroot->right) && isBool(Lroot->right,Rroot->left);
}
return false;
}
};
迭代法
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
private:
queue<TreeNode*> q;
public:
bool isSymmetric(TreeNode* root) {
if(root == NULL) return true;
if(!root->left && !root->right) return true; //左右结点都空时
if(!root->left || !root->right) return false; //有一个结点为空时
if(root->left && root->right)
{
q.push(root->left);
q.push(root->right);
}
while(!q.empty())
{
TreeNode* l = q.front();
q.pop();
TreeNode* r = q.front();
q.pop();
if(l->val == r->val)
{
if(l->left && r->right)
{
q.push(l->left);
q.push(r->right);
}
else if(l->left || r->right)
return false;
if(l->right && r->left)
{
q.push(l->right);
q.push(r->left);
}
else if(l->right || r->left)
return false;
}
else
return false;
}
return true;
}
};