c语言用二叉链表创建一个深度为4的非完全二叉树,并用先序和层序遍历
时间: 2024-05-02 16:19:49 浏览: 73
c实现二叉树先序层序遍历
5星 · 资源好评率100%
这是一个技术问题,我可以为您解答。以下是代码示例:
```c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct Node {
char data;
struct Node* lchild;
struct Node* rchild;
} Node;
Node* create(char data) {
Node* node = (Node*)malloc(sizeof(Node));
node->data = data;
node->lchild = NULL;
node->rchild = NULL;
return node;
}
void preOrder(Node* node) {
if (node == NULL) {
return;
}
printf("%c ", node->data);
preOrder(node->lchild);
preOrder(node->rchild);
}
void levelOrder(Node* root) {
Node** queue = (Node**)malloc(sizeof(Node*) * 100);
int head = 0;
int tail = 0;
queue[tail++] = root;
while (head != tail) {
Node* node = queue[head++];
printf("%c ", node->data);
if (node->lchild != NULL) {
queue[tail++] = node->lchild;
}
if (node->rchild != NULL) {
queue[tail++] = node->rchild;
}
}
}
int main() {
Node* root = create('A');
Node* b = create('B');
Node* c = create('C');
Node* d = create('D');
Node* e = create('E');
Node* f = create('F');
Node* g = create('G');
Node* h = create('H');
Node* i = create('I');
Node* j = create('J');
Node* k = create('K');
Node* l = create('L');
Node* m = create('M');
root->lchild = b;
root->rchild = c;
b->lchild = d;
b->rchild = e;
c->lchild = f;
c->rchild = g;
d->lchild = h;
e->rchild = i;
f->rchild = j;
g->rchild = k;
h->rchild = l;
k->lchild = m;
printf("先序遍历:");
preOrder(root);
printf("\n");
printf("层序遍历:");
levelOrder(root);
printf("\n");
return 0;
}
```
上面的代码创建了一个深度为 4 的非完全二叉树,使用先序遍历和层序遍历分别输出了每个节点的值。您可以根据需要修改节点数据和结构来创建其他树形结构。
阅读全文