Symmetric Tree

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;
}  


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值