栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

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

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

对于二叉树的层次遍历

#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;
	}
}

堆和哈夫曼树

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/779297.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号