对于二叉树的层次遍历
#include#include #include using namespace std; typedef struct node{ char data; node* lchild; node* rchild; }node; void BFS(node* n1) { queue q; if(n1!=NULL) { q.push(n1); } while(!q.empty()) { node* n2=q.front(); cout< data< lchild!=NULL) { q.push(n2->lchild); } if(n2->rchild!=NULL) { q.push(n2->rchild); } } } node* init(char c) { node* n=new node; n->data=c; n->lchild=NULL; n->rchild=NULL; } int main() { node* root=init('A'); root->lchild=init('C'); root->rchild=init('B'); BFS(root); return 0; }
根据中序序列和先序序列或后序序列构建一棵二叉树
//当先序序列区间为[preL,preR],中序序列为[inL,inR],返回根节点地址
node* creat(int preL,int preR,int inL,int inR)
{
if(preL>preR)
{
return NULL;
}
node* root=new node;
root->data=pre[preL];
int k;
for(k=inL;k<=inR;k++)
{
if(in[k]==pre[preL])
{
break;
}
}
int numLeft=k-inL;
root->lchild=creat(preL+1,preL+numLeft,inL,k-1);
root->rchild=creat(preL+numLeft+1,preR,k+1,inR);
return root;
}
//当后序序列区间为[postL,postR],中序序列为[inL,inR],返回根节点地址
node* creat(int preL,int preR,int inL,int inR)
{
if(postL>psotR)
{
return NULL;
}
node* root=new node;
root->data=pre[postR];
int k;
for(k=inL;k<=inR;k++)
{
if(in[k]==post[postR])
{
break;
}
}
int numLeft=k-inL;
root->lchild=creat(preL,preL+numLeft-1,inL,k-1);
root->rchild=creat(preL+numLeft,preR-1,k+1,inR);
return root;
}
对于并查集的基本操作:
初始化
for(int i=1;i<=N;i++)
{
father[i]=i;
}
查找
//返回元素x所在集合的根节点
int findfather(int x)
{
while(x!=father[x])
{
x=father[x];
}
return x;
}
合并两个集合
void Union(int a,int b)
{
int faA=findfather(a);
int faB=findfather(b);
if(faA!=faB)
{
father[faA]=faB;
}
}
路径合并(将子节点的父节点设置为根节点)
//路径压缩(将上面的查找部分代码改写)
int findfather()
{
if(v==father[v])
{
return v;
}
else
{
int F=findfather(father[v]);
father[v]=F;
return F;
}
}
堆和哈夫曼树



