/****************************************************/
/* huffman树 */
/****************************************************/
linkhuf Creat_Node(int n) //创建一单链表
{
linkhuf head,pre,p;
int x;
head=NULL;
while(n--)
{
scanf("%d",&x);
p=(linkhuf)malloc(sizeof(hufnode));
p->data=x;
p->lchild=NULL;
p->rchild=NULL;
if(NULL==head)
{
head=p;
pre=head;
}
else
{
p->next=pre->next;
pre->next=p;
pre=pre->next;
}
}
return head;
}
linkhuf insert(linkhuf root , linkhuf s)//将结点S插入到有序Huffman root中。
{
linkhuf p1,p2;
if(NULL == root ) root=s;
else
{
p1=NULL;
p2=root;
while(p2&&p2->data<s->data)
{
p1=p2;
p2=p2->next;
}
s->next=p2;
if(NULL==p1)
{
root=s;
}
else
{
p1->next=s;
}
}
return root;
}
void Preorder1(linkhuf t)
{
if(t!=NULL)
{
printf("%-6d",t->data);
Preorder1(t->lchild);
Preorder1(t->rchild);
}
}
void creathuffman(linkhuf *root)//构造Huffman树。
{
linkhuf s, rl,rr;
while(*root && (*root)->next)
{
rl=*root;
rr=(*root)->next;
*root=rr->next;
s=(linkhuf)malloc(sizeof(hufnode));
s->next=NULL;
s->data=rl->data+rr->data;
s->lchild=rl;
s->rchild=rr;
rl->next=rr->next=NULL;
*root=insert(*root,s);
}
}
int main()
{
linkhuf root;
int n;
scanf("%d",&n);
root=Creat_Node(n);
creathuffman(&root);
Preorder1(root);
printf("/n");
return 0;
}
/************************************************************/
/* 按层次顺序建立一棵二叉树 */
/************************************************************/
#include"Bintree.h"
Bintree Level_Creat()
{
Bintree root,p,s;
queue node;
node.front=node.rear=0;
char ch;
ch=getchar();
if(ch==' ')
{
return NULL;
}
root=(Binnode*)malloc(sizeof(Binnode)); //生成根结点
root->data=ch;
node.data[node.rear++]=root; //用队列实现层次遍历
while(node.front<node.rear)
{
p=node.data[node.front++];
ch=getchar(); //为了简化操作,分别对左右子结点进行赋值。
if(ch!=' ')//子树不空则进队列进行扩充。下同
{
s=(Binnode*)malloc(sizeof(Binnode));
s->data=ch;
p->lchild=s;
node.data[node.rear++]=s;
}
else
{
p->lchild=NULL;
}
ch=getchar();
if(ch!=' ')
{
s=(Binnode*)malloc(sizeof(Binnode));
s->data=ch;
p->rchild=s;
node.data[node.rear++]=s;
}
else
{
p->rchild=NULL;
}
}
return root;
}
int main()
{
Bintree root;
root=Level_Creat();
Inorder1(root);//测试,中序遍历
return 0;
}