问题描述:
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
示例:
For example, this binary tree [1,2,2,3,4,4,3]
is symmetric:
1 / \ 2 2 / \ / \ 3 4 4 3
But the following [1,2,2,null,3,null,3]
is not:
1 / \ 2 2 \ \ 3 3
问题分析:
本题可以看作SameTree的一个变体,详细分析可参考我的Same Tree问题及解法
下面是详细代码:
/**
* 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) {
return isSameTree(root,root);
}
bool isSameTree(TreeNode* p, TreeNode* q) {
if(p == NULL && q == NULL) return true;
else if(p == NULL) return false;
else if(q == NULL) return false;
if(p->val == q->val)
{
return isSameTree(p->left,q->right) && isSameTree(p->right,q->left);
}
else return false;
}
};
有疑问欢迎交流~~