一般意义的树的基本操作(使用静态链表)

点击查看代码
#include<cstdio>
#include<vector>
#include<queue>
using namespace std;
#pragma warning(disable:4996) 
const int maxn = 100;
 /*
struct node { //一般意义的树的结点定义
	int data; //数据域
	//int child[maxn]; //指针域,存储孩子结点下标(因为不知道有几个孩子,所以大小设为maxn)
	vector<int> child; //使用vector容器存储孩子结点下标,需要时自动扩充容量
}Node[maxn]; //结点数组,maxn是结点个数上限

//新建结点
int index = 0; //结点编号,即数组下标
int newNode(int v) {
	Node[index].data = v; //结点权值为v
	Node[index].child.clear(); //清空孩子结点
	return index++; //返回结点编号,然后index加一作为下一个结点编号
}

//树的先根遍历
void preorder(int root) {
	printf("%d", Node[root].data); //访问当前结点数据域
	for (int i = 0; i < Node[root].child.size(); i++) {
		preorder(Node[root].child[i]); //递归访问结点root的所有孩子结点
	}
}	*/ 

//树的层序遍历,如果需要对结点的层号进行求解,则在结点node定义中加入int layer
struct node { //一般意义的树的结点定义
	int layer; //结点层号
	int data; //数据域
	vector<int> child; //使用vector容器存储孩子结点下标,需要时自动扩充容量
}Node[maxn]; //结点数组,maxn是结点个数上限

void layerorder(int root) {
	queue<int> q; //定义队列q
	q.push(root); //将根结点入队
	Node[root].layer = 0; //根结点层号为0
	while (!q.empty()) { //只要队列q非空,就继续循环
		int front = q.front(); //将队首元素存入front中	
		q.pop(); //队首元素出队后,要手动删除
		printf("%d ", Node[front].data); //访问当前结点数据域
		for (int i = 0; i < Node[front].child.size(); i++) {
			int child = Node[front].child[i]; //当前结点的第i个孩子结点编号存入child中
			//孩子结点层号为当前结点层号加一
			Node[child].layer = Node[front].layer + 1;
			q.push(child); //将当前结点的所有孩子结点入队
		}
	}
}

posted @ 2022-09-30 21:08  zhaoo_o  阅读(6)  评论(0编辑  收藏  举报