题目描述:请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。
A / B B / / C D D C
C++代码:
//普通递归方法
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
class Solution {
public:
bool isSymmetrical(TreeNode* pRoot)
{
if (pRoot == NULL)return true;
return isSymmetrical(pRoot, pRoot);
}
bool isSymmetrical(TreeNode* pRoot1, TreeNode* pRoot2)
{
if (pRoot1 == NULL && pRoot2 == NULL)
return true;
if ((pRoot1 == NULL || pRoot2 == NULL))return false;
if (pRoot1->val != pRoot2->val)return false;
return isSymmetrical(pRoot1->left, pRoot2->right) && isSymmetrical(pRoot1->right, pRoot2->left);
}
};
//使用队列
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
class Solution {
public:
bool isSymmetric(TreeNode* root) {
if(root==NULL) return true;
queue<TreeNode*> q1,q2;
TreeNode *left,*right;
q1.push(root->left);
q2.push(root->right);
while(!q1.empty() and !q2.empty())
{
left = q1.front();
q1.pop();
right = q2.front();
q2.pop();
//两边都是空
if(NULL==left && NULL==right)
continue;
//只有一边是空
if(NULL==left||NULL==right)
return false;
if (left->val != right->val)
return false;
q1.push(left->left);
q1.push(left->right);
q2.push(right->right);
q2.push(right->left);
}
return true;
}
};
//使用栈
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
class Solution {
public:
bool isSymmetrical(TreeNode* pRoot)
{
stack<TreeNode*> s1,s2;
TreeNode *p1,*p2;
p1=p2=pRoot;
while((!s1.empty()&&!s2.empty())||(p1!=NULL&&p2!=NULL)){
while(p1!=NULL&&p2!=NULL){
s1.push(p1);
s2.push(p2);
p1=p1->left;
p2=p2->right;
}
p1=s1.top();
s1.pop();
p2=s2.top();
s2.pop();
if(p1->val!=p2->val)
return false;
p1=p1->right;
p2=p2->left;
}
if(!s1.empty()||!s2.empty())
return false;
if(p1!=NULL||p2!=NULL)
return false;
return true;
}
};