Symmetric Tree
Total Accepted: 83908 Total Submissions: 257485 Difficulty: Easy
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
思路:
1).还是得先判断是否为NULL,否则root->val就没有意义。
2).接着定义一个重载函数isSymmetric(TreeNode* left,TreeNode* right),用来判断left与right是否相等。不等返回false,相等则返回isSymmetric(left->right,right->left)&&isSymmetric(left->left,right->right)。即不断递归,判断每层是否对称。
/**
* 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* left,TreeNode* right){
if(left==NULL&&right==NULL){
return true;
}else if(left==NULL){
return false;
}else if(right==NULL){
return false;
}
if(left->val==right->val){
return (isSymmetric(left->left,right->right)&&isSymmetric(left->right,right->left));
}else{
return false;
}
}
bool isSymmetric(TreeNode* root) {
if(root==NULL){
return true;
}else{
return isSymmetric(root->left,root->right);
}
}
};