1.数组实现二叉树的遍历
#include<iostream>
using namespace std;
int len=9;
void prefind(int n[],int i)
{
if(i>=len)
return;
cout<<n[i]<<" ";
prefind(n,i*2+1);
prefind(n,i*2+2);
}
void midfind(int n[],int i)
{
if(i>=len)
return;
midfind(n,i*2+1);
cout<<n[i]<<" ";
midfind(n,i*2+2);
}
void endfind(int n[],int i)
{
if(i>=len)
return;
endfind(n,i*2+1);
endfind(n,i*2+2);
cout<<n[i]<<" ";
}
int main()
{
int n[]={78,56,34,43,4,1,15,2,23};
prefind(n,0);
cout<<endl;
midfind(n,0);
cout<<endl;
endfind(n,0);
return 0;
}
堆排序
小根堆
#include<iostream>
using namespace std;
const int N=1e5+5;
int s[N],sizes;
void down(int k)
{
int t=k;
if(k*2<=sizes&&s[k*2]<s[t]) t=k*2;
if(k*2+1<=sizes&&s[k*2+1]<s[t]) t=k*2+1;
if(k!=t)
{
swap(s[k],s[t]);
down(t);
}
}
int main()
{
int n,m;
cin>>n>>m;
for(int i=1;i<=n;i++) cin>>s[i];
sizes=n;
for(int i=n/2;i;i--)
{
down(i);
}
while(m--)
{
cout<<s[1]<<" ";
s[1]=s[sizes];
sizes--;
down(1);
}
return 0;
}
1.堆的插入
head[++size]=x;
up(size);
2.求最小值(小根堆)
heap[1];
3.删除最小值
head[k]=heap[size];size–;down(1);
4.删除任一元素
heap[k]=heap[size];size–;down(k);up(k);
5.修改任意元素
heap[k]=x;down(k);up(k);
大根堆
#include<iostream>
using namespace std;
const int N=1e5+5;
int s[N],sizes;
void up(int k)
{
int t=k;
if(k*2<=sizes&&s[k*2]>s[t]) t=k*2;
if(k*2+1<=sizes&&s[k*2+1]>s[t]) t=k*2+1;
if(k!=t)
{
swap(s[k],s[t]);
up(t);
}
}
int main()
{
int n,m;
cin>>n>>m;
for(int i=1;i<=n;i++) cin>>s[i];
sizes=n;
for(int i=n/2;i;i--)
{
up(i);
}
while(m--)
{
cout<<s[1]<<" ";
s[1]=s[sizes];
sizes--;
up(1);
}
return 0;
}