请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。
题目地址https://www.nowcoder.com/study/live/173/1/2
//核心算法
bool fun(TreeNode *a,TreeNode *b){
if(!a&&!b)return true;
if(!a||!b)return false;
if(a->val!=b->val)return false;
return fun(a->left,b->right)&&fun(a->right,b->left);
}
//验证主程序
#include<stdio.h>
#include<iostream>
#define R 100
using namespace std;
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
class Solution {
public:
bool isSymmetrical(TreeNode* pRoot)
{
return fun(pRoot,pRoot);
}
bool fun(TreeNode *a,TreeNode *b){
if(!a&&!b)return true;
if(!a||!b)return false;
if(a->val!=b->val)return false;
return fun(a->left,b->right)&&fun(a->right,b->left);
}
};
void ShowNode(TreeNode *p){
printf("p->point=%d\n",p);
printf("p->val=%d\n",p->val);
printf("p->left=%d\n",p->left);
printf("p->right=%d\n\n",p->right);
}
TreeNode *CreatTree(int value,TreeNode *left,TreeNode *right){
TreeNode *s = new TreeNode(value);
s->left = left;
s->right = right;
ShowNode(s);
return s;
}
int main(){
TreeNode *a,*b,*c,*d,*e;
Solution *solu = new Solution;
d=CreatTree(2,NULL,NULL);
e=CreatTree(2,NULL,NULL);
b=CreatTree(4,d,NULL);
c=CreatTree(4,NULL,e);
a=CreatTree(10,b,c);
printf("out = %d",solu->isSymmetrical(a));
return 0;
}