对称二叉树
Problem Description
如果二叉树的左右子树的结构是对称的,即两棵子树皆为空,或者皆不空,则称该二叉树是对称的。判断给定的二叉树是否对称。二叉树用层序结构给出,若读到#则为空,如果二叉树是对称的,输出“Yes”,反之输出“ No”。
Input
输入有多组数据,每组数据只有一行为二叉树的层序结构字符串,长度不大于100。
Output
对于每组数据如果二叉树是对称的,输出“Yes”,反之输出“ No”。Sample Input
ABCDE
ABCD#E
Sample Output
Yes
No
#include<iostream>
#include<stack>
#define N 110//定义宏并非多此一举,建议善用宏
using namespace std;
char str[N];
int len;//字符串的长度
struct BTreeNode
{
char data;//data的类型依题意而定
BTreeNode *lchild;
BTreeNode *rchild;
};
BTreeNode *Create(int n)//创建二叉树
{
if('#'==str[n] || n>=len)
return 0;//建议用0取代NULL;
else
{
BTreeNode *current=new BTreeNode;//建立新的节点
current->data=str[n];//当前节点的值
current->lchild=Create((n<<1)+1);//此题给出的顺序为层序遍历,所以左孩子为2*n+1
current->rchild=Create((n<<1)+2);//右孩子为2*n+2;
return current;
}
}
void FreeBT(BTreeNode *root)//释放函数
{
if(root!=0)
{
FreeBT(root->lchild);
FreeBT(root->rchild);//当左右孩子都为空的时候,释放空间
delete root;
}
}
void Check(BTreeNode *root)//遍历查找函数,根据前序遍历改动
{
stack<BTreeNode *> s;
int flag=0;
s.push(root);
while(!s.empty())
{
root=s.top();
s.pop();
if((0==root->lchild && 0!=root->rchild) || (0!=root->lchild) && (0==root->rchild))
//(左孩子为空,右孩子非空)或者(左孩子为空,右孩子非空)
{
flag=1;
break;
}
else if(0!=root->rchild)//注意栈的先进后出性质,所以先检测右孩子
{
s.push(root->rchild);
}
else if(0!=root->lchild)
{
s.push(root->lchild);
}
}
if(0==flag)
{
puts("Yes");
}
else
{
puts("N0");
}
}
int main()
{
while(scanf("%s",str)!=EOF)
{
len=strlen(str);
BTreeNode *root=Create(0);
Check(root);
FreeBT(root);
}
return 0;
}
欢迎加入反汇编群:559489647