#include<iostream>
#include<string.h>
using namespace std;
struct node
{
char data;
node *lchild,*rchild;
};
//dbgeafc
//dgebfca
node *creatTree()//一行建立二叉树
{
node *root;
top++;
if(a[top]==',')
return NULL;
else
{
root=new node;
root->data=a[top];
root->lchild=creatTree();
root->rchild=creatTree();
}
return root;
}
node *createTreexz(char a[],int n,char b[])//已知先序和中序建立二叉树
{
if(n<=0)
return NULL;
node *root=new node;
root->data=a[0];
int i;
for(i=0; i<n; i++)
if(a[0]==b[i]) break;
root->lchild=createTreexz(a+1,i,b);
root->rchild=createTreexz(a+i+1,n-i-1,b+i+1);
return root;
}
node *createTree(char a[],int n,char b[])//已知中序和后序建立二叉树
{
if(n<=0)
return NULL;
node *root;
root=new node;
root->data=b[n-1];
int i;
for(i=0; i<n; i++)
if(a[i]==b[n-1]) break;
root->lchild=createTree(a,i,b);
root->rchild=createTree(a+i+1,n-i-1,b+i);
return root;
}
void xb(node *head)//先序遍历
{
if(head==NULL)
return ;
else
{
cout<<head->data;
xb(head->lchild);
xb(head->rchild);
}
}
int depth(node *head)//求二叉树深度
{
int m,n;**//若定义为全局变量会WR**
if(head==NULL)
return 0;
else
{
m=depth(head->lchild);
n=depth(head->rchild);
if(m>n) return m+1;
else
return n+1;
}
}
int leaves(node *head)//叶子数
{
if(head==NULL)
return 0;
else if(head->lchild==NULL&&head->rchild==NULL)
return 1;
else
return leaves(head->lchild)+leaves(head->rchild);
}
void cengcibianli(node *t)//层次遍历
{
if(t==NULL) return ;
queue<node*>q;
q.push(t);
while(q.empty()==false)//如果队列不是空,继续执行
{
node *x=q.front();//返回第一个元素
cout<<x->data;//输出
q.pop();//删除第一个元素
if(x->lchild!=NULL)
q.push(x->lchild);//左孩子入队
if(x->rchild!=NULL)
q.push(x->rchild);//右孩子入队
}
}
void cengcibianli(node *t)//层次遍历
{
node *a[10000];
int in,out;
in=out=0;
a[in++]=t;//将根节点导入
while(in>out)
{
if(a[out])
{
cout<<a[out]->date;
a[in++]=a[out]->lchild;
a[in++]=a[out]->rchild;
}
out++;
}
}
int main()
{
node *root;
int n;
char a[100],b[100];
cin>>n;
while(n--)
{
cin>>a;
cin>>b;
int len=strlen(a);
root=createTree(a,len,b);
xb(root);
cout<<endl;
}
return 0;
}
二叉树的各种操作汇总
猜你喜欢
转载自blog.csdn.net/JdiLfc/article/details/108677265
今日推荐
周排行