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
题意;给定一个二叉树,判断是否为中心对称。上述第一图为对称树,第二为非对称树。
分析上图,我们发现,当前左右节点相等,并且他们的子树也对称,那么整棵树也是对称的。
最简单的,我们可以用递归来给出答案。
以下是我的C++版本。
/**
* 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 myEqual(TreeNode *left, TreeNode *right){
if(left == NULL && right == NULL) return true;
if(left == NULL || right == NULL) return false;
return ((left->val == right->val) && myEqual(left->left, right->right) && myEqual(left->right, right->left));
}
bool isSymmetric(TreeNode *root) {
if(root == NULL) return true;
return myEqual(root->left, root->right);
}
};