标签:小代码
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <queue>
#include <math.h>
using namespace std;
typedef struct BTNode
{
int data;
struct BTNode *lc;
struct BTNode *rc;
}BTNode,*BiTree;
int ss[]={1,3,5,-1,-1,2,-1,-1,4,6,-1,-1,-1};
int a[]={0,1,3,5,2,4,6};
int k=0;
void array()
{ k=0;
int i=0; int t[]={1,2,3,-1,-1,4,5,6,-1,-1,-1};
for(i=0;i<11;i++)
{
ss[i]=t[i];cout<<ss[i]<<" ";
}
}
void Creat(BiTree &T)
{
int x;
x=ss[k++];
if (x==-1) T=NULL;
else{
T=new BTNode;
T->data=x;
Creat(T->lc);
Creat(T->rc);
}
}
void print_as_tree(BiTree T,int lay)
{
if(T)
{
print_as_tree(T->lc,lay+1);
for(int j=0;j<lay;j++)printf("*");cout<<T->data<<endl;
print_as_tree(T->rc,lay+1);
}
else return;
}
void lay(BiTree root,int n) /*/ 层次打印 /*/
{ //assert(root)
int k=1; int m=1;int i=0;
BiTree b=root;
queue<BiTree> q;
q.push(b);
while(!q.empty())
{
b=q.front(); if(b->lc) q.push(b->lc); if(b->rc) q.push(b->rc);
m=pow(2,k-1); for(i=0;i<n/2;i++) cout<<" ";cout<<b->data; q.pop();
while(--m)
{
for(i=0;i<2*(n/2)+1;i++) cout<<" ";
if(!q.empty())
{ b=q.front();
if(b->lc) q.push(b->lc);
if(b->rc) q.push(b->rc);
cout<<b->data; q.pop();
}
else cout<<"#";
}
cout<<endl;
n=n/2;
k++;
}
cout<<endl;
}
void HeapAdjust(int *a,int i,int size) //调整堆
{
int lchild=2*i; //i的左孩子节点序号
int rchild=2*i+1; //i的右孩子节点序号
int max=i; //临时变量
if(i<=size/2) //如果i是叶节点就不用进行调整
{
if(lchild<=size&&a[lchild]>a[max])
{
max=lchild;
}
if(rchild<=size&&a[rchild]>a[max])
{
max=rchild;
}
if(max!=i)
{
swap(a[i],a[max]);
HeapAdjust(a,max,size); //避免调整之后以max为父节点的子树不是堆
}
}
}
void BuildHeap(int *a,int size) //建立堆
{
int i;
for(i=size/2;i>=1;i--) //非叶节点最大序号值为size/2
{
HeapAdjust(a,i,size);
}
}
void HeapSort(int *a,int size) //堆排序
{
int i;
BuildHeap(a,size);
for(i=size;i>=1;i--)
{
//cout<<a[1]<<" ";
swap(a[1],a[i]); //交换堆顶和最后一个元素,即每次将剩余元素中的最大者放到最后面
//BuildHeap(a,i-1); //将余下元素重新建立为大顶堆
HeapAdjust(a,1,i-1); //重新调整堆顶节点成为大顶堆
}
}
int main(int argc, char *argv[])
{
int size=6,i;
BiTree S; BiTree T;
Creat(S);
lay(S,3);
print_as_tree(S,3);
HeapSort(a,size);
for(i=1;i<=size;i++)
cout<<a[i]<<" ";
cout<<endl;
k=0;
array(); cout<<endl;
k=0;Creat(T);
lay(T,3);
print_as_tree(T,3);
return 0;
}
/*************************
http://anycodes.cn/zh/*************************/ 1 3 4 5 2 6 # *****5 ****3 *****2 ***1 *****6 ****4 1 2 3 4 5 6 1 2 3 -1 -1 4 5 6 -1 -1 -1 1 2 3 4 5 6 # *****3 ****2 *******6 ******5 *****4 ***1 //待更好设计 来演示
标签:小代码
原文地址:http://wzsts.blog.51cto.com/10251779/1770254