C 如何在BFS中打印trenary树?
我有一棵树:C 如何在BFS中打印trenary树?,c,C,我有一棵树: typedef struct Trin_Ari { int id; char* name; struct Trin_Ari *parent; struct Trin_Ari *left; struct Trin_Ari *middle; struct Trin_Ari *right; }Trin_Ari; 我的成员顺序如下: 我需要这样打印: A1 B2 D4 G7 C3 E5 F6 H8 I9 级别顺序树遍历。 从根节点开始 对于每个节点 打印节点数据 将子项(如果有)
typedef struct Trin_Ari {
int id;
char* name;
struct Trin_Ari *parent;
struct Trin_Ari *left;
struct Trin_Ari *middle;
struct Trin_Ari *right;
}Trin_Ari;
我的成员顺序如下:
我需要这样打印:
A1
B2
D4
G7
C3
E5
F6
H8
I9
级别顺序树遍历。
- 从根节点开始
- 对于每个节点
- 打印节点数据
- 将子项(如果有)推到队列中(排队-从左到右)
- 从队列中获取下一个元素(出列)
// for test purpose
#define MAX_NODES 32
static struct {
int head, tail;
Trin_Ari* data[MAX_NODES]; // or allocate at runtime
} queue;
static void reset_queue()
{
queue.head = queue.tail = 0;
memset(queue.data, 0, sizeof(Trin_Ari*) * MAX_NODES);
}
static void enqueue(Trin_Ari *node)
{
queue.data[queue.tail++] = node;
}
static Trin_Ari* dequeue()
{
return queue.data[queue.head++];
}
void print(Trin_Ari *root)
{
Trin_Ari *node = root;
reset_queue();
while (node) {
// print node data
printf("%i, %s\n", node->id, node->name);
// enqueue child nodes
if (node->left) enqueue(node->left);
if (node->middle) enqueue(node->middle);
if (node->right) enqueue(node->right);
// dequeue a node from the queue
node = dequeue();
}
}
对于树:
A
/ | \
B C D
/ | \ / | \ / | \
E F G H I J K L M
1。迭代
- 印刷品:A
- 队列:B C D//已排队
- 节点:B//已退出队列
- 印刷品:B
- 队列:B C D E F G
- 节点:C
- 印刷品:C
- 队列:B C D E F G H I J
- 节点:D
- 印刷品:D
- 队列:B C D E F G H I J K L M
- 节点:E
- 印刷品:E
- 队列:B C D E F G H I J K L M//注意:绘图缺少节点
。您特别询问三元树。你知道用二叉树做吗?你在尝试时遇到的障碍是什么。我之所以这样问,是因为你的问题并没有显示出你自己的努力,似乎只是在问代码。它也不清楚你需要的细节水平,从零开始,似乎是因为没有演示任何东西,但标题显然侧重于三元树。。。。G,H,I