递归方法:
</pre><p></p><pre name="code" class="cpp">/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isSymmetricCore(TreeNode *pNode1, TreeNode *pNode2) {
if(pNode1 == NULL && pNode2 == NULL)
return true;
if(pNode1 == NULL || pNode2 == NULL)
return false;
if(pNode1->val != pNode2->val)
return false;
else if(!isSymmetricCore(pNode1->left, pNode2->right))
return false;
else
return isSymmetricCore(pNode1->right, pNode2->left);
}
bool isSymmetric(TreeNode *root) {
bool isSymmetric = true;
if(root != NULL)
{
isSymmetric = isSymmetricCore(root->left, root->right);
}
return isSymmetric;
}
};
循环方法:
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
#include<queue>
using namespace std;
typedef pair<TreeNode*,TreeNode*> nodepair;
class Solution {
public:
bool isSymmetric(TreeNode *root) {
// Level-order BFS.
queue<nodepair> q;
if(root)
q.push(make_pair(root->left,root->right));
while(q.size()){
nodepair p=q.front(); q.pop();
if(p.first){
if(!p.second)return false;
if(p.first->val != p.second->val) return false;
// the order of children pushed to q is the key to the solution.
q.push(make_pair(p.first->left,p.second->right));
q.push(make_pair(p.first->right,p.second->left));
}
else if(p.second) return false;
}
return true;
}
};