《算法笔记》 第九章 提高篇(3)---数据结构专题(2)

对于二叉树的层次遍历

#include <iostream>
#include <cstdio>
#include <queue>
using namespace std;

typedef struct node{
	char data;
	node* lchild;
	node* rchild;
}node;

void BFS(node* n1)
{
	queue<node*> q;
	if(n1!=NULL)
	{
		q.push(n1);
	}
	while(!q.empty())
	{
		node* n2=q.front();
		cout<<n2->data<<endl;
		q.pop();
		if(n2->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;
	}
}

堆和哈夫曼树

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值