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
#include <iostream>
#include <stdlib.h>
using namespace std;
/**
* Definition for binary tree
*/
struct TreeNode {
char val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
//前序法创建二叉树
void CreateBiTree(TreeNode* &T,char* &str) {
if(*str++=='#')
T=NULL;
else {
T=(TreeNode*)malloc(sizeof(TreeNode));
if(!T) exit(1);
T->val=*(str-1);
CreateBiTree(T->left,str); //构造左子树
CreateBiTree(T->right,str); //构造右子树
}
}
//递归检测左右对称的节点
bool isCheck(TreeNode *l,TreeNode *r) {
if(l == NULL && r == NULL)
return true;
else if(l == NULL || r == NULL)
return false;
if(l->val != r->val)
return false;
//两节点均不为空且值相等,则递归判断它们的孩子节点
return (isCheck(l->left,r->right) && isCheck(l->right,r->left));
}
//判断树是否是对称的
bool isSymmetric(TreeNode *root) {
if(root == NULL)
return true;
return isCheck(root->left,root->right);
}
int main()
{
TreeNode *T1,*T2;
char* ch;
char case1[]={"ABC##DE#G##F###"}; //非对称树
char case2[]={"ABC##D##BD##C##"}; //对称树
ch=case1;
CreateBiTree(T1,ch);
ch=case2;
CreateBiTree(T2,ch);
cout << isSymmetric(T1) << endl;
cout << isSymmetric(T2) << endl;
return 0;
}