题目:
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
1
/ \
2 2
/ \ / \
3 4 4 3
But the following is not:
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 NodePair {
public:
NodePair(TreeNode* a, TreeNode* b) : pa(a), pb(b) {}
bool isMirror() {
bool a = (pa->left && pb->right && pa->left->val == pb->right->val) || (!pa->left && !pb->right);
bool b = (pb->left && pa->right && pb->left->val == pa->right->val) || (!pb->left && !pa->right);
return a && b;
}
TreeNode* pa;
TreeNode* pb;
};
class Solution {
public:
bool isSymmetric(TreeNode* root) {
if (!root) {
return true;
}
NodePair rootPair(root, root);
if (!rootPair.isMirror()) {
return false;
}
if (!root->left) {
return true;
}
list<NodePair> myList;
NodePair pair(root->left, root->right);
myList.push_back(pair);
for (list<NodePair>::iterator it = myList.begin(); it != myList.end(); ++it) {
if(!it->isMirror()) {
return false;
}
if(it->pa->left) {
NodePair pair(it->pa->left, it->pb->right);
myList.push_back(pair);
}
if(it->pa->right) {
NodePair pair(it->pa->right, it->pb->left);
myList.push_back(pair);
}
}
return true;
}
};