#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
typedef struct node tree;
struct node
{
char data;
struct node *left;
struct node *right;
};
tree *root;
char ch;
string str;
int i=0;
tree *CreateBinTree()
{
tree *p;
if(str[i++]==',')
p=NULL;
else
{
p=new tree;
p->data=str[i-1];
p->left=CreateBinTree();
p->right=CreateBinTree();
}
return p;
}
void mid_order(tree *root)
{
if(root)
{
mid_order(root->left);
cout<<root->data;
mid_order(root->right);
}
}
void post_order(tree *root)
{
if(root)
{
post_order(root->left);
post_order(root->right);
cout<<root->data;
}
}
int yenum(tree *root)
{
if(root==NULL)
return 0;
else if(root->left==NULL&&root->right==NULL)
return 1;
else
return yenum(root->left)+yenum(root->right);
}
int shendu(tree *root)
{
if(!root)
return 0;
else
return max(1+shendu(root->left),1+shendu(root->right));
}
queue<tree*>que;
void cengxu(tree *root)
{
tree *p;
if(root==NULL) return;
que.push(root);
while(!que.empty())
{
p=que.front();
que.pop();
//if(p->left==NULL&&p->right==NULL)//用于只输出叶节点
cout<<p->data;
if(p->left) que.push(p->left);
if(p->right) que.push(p->right);
}
}
tree *huanyuan(int n,char a[],char b[])
{
tree *p;
p=new tree;
if(n==0)
p=NULL;
else
{
int i;
for(i=0;i<n;++i)
{
if(a[0]==b[i])
{
break;
}
}
p->data=b[i];
p->left=huanyuan(i,a+1,b);
p->right=huanyuan(n-i-1,a+i+1,b+i+1);
}
return p;
}
void pre_order(tree *root)
{
if(root)
{
cout<<root->data;
pre_order(root->left);
pre_order(root->right);
}
}
int main()
{
char a[55],b[55];
int n,t;
cin>>t;
while(t--)
{
cin>>a>>b;
n=strlen(a);
root=NULL;
root=huanyuan(n,a,b);
root=CreateBinTree();
pre_order(root);
cout<<endl;
mid_order(root);
cout<<endl;
post_order(root);
cout<<endl;
cout<<yenum(root)<<endl;
cout<<shendu(root)<<endl;
cengxu(root);
cout<<endl;
}
return 0;
}
二叉树的部分基础操作
最新推荐文章于 2025-04-19 20:53:03 发布