1、树节点的定义方式
2、树节点的创建
3、树的前序遍历
4、树的层序遍历
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
const int maxn = 100;
struct node
{
int data; // 存放当前节点的数据
int layer; // 当前节点的层次
vector<int> child; // 存放所有子节点的下标
}tree[maxn];
int index = 0;
int newNode(int v)
{
tree[index].data = v;
tree[index].child.clear();
return index++;
}
// 树的先序遍历
void preorder(int root)
{
printf("%d ", tree[root].data);
int len = tree[root].child.size();
for (int i = 0; i < len; ++i)
{
preorder(tree[root].child[i]);
}
}
// 树的层序遍历
void layerOrder(int root)
{
queue<int> q;
q.push(root);
tree[root].layer = 0; // 根节点的层号为0
while (!q.empty())
{
int loc = q.front();
printf("layer = %d, data = %d\n", tree[loc].layer, tree[loc].data);
int len = tree[loc].child.size();
for (int i = 0; i < len; ++i)
{
int child = tree[loc].child[i];
tree[child].layer = tree[loc].layer + 1;
q.push(child);
}
}
}
int main()
{
return 0;
}
谢谢阅读