用c语言实现二叉树的建立对二叉树对二叉树进行先序遍历,并打印层号
时间: 2023-11-14 16:09:11 浏览: 112
下面是用C语言实现二叉树的建立和先序遍历,并打印层号的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int val;
struct Node *left;
struct Node *right;
} Node;
void buildTree(Node **root) {
int val;
scanf("%d", &val);
if (val == -1) {
*root = NULL;
} else {
*root = (Node*)malloc(sizeof(Node));
(*root)->val = val;
buildTree(&((*root)->left));
buildTree(&((*root)->right));
}
}
void preorder(Node *root, int level) {
if (root == NULL) {
return;
}
printf("Level %d: %d\n", level, root->val);
preorder(root->left, level + 1);
preorder(root->right, level + 1);
}
int main() {
Node *root = NULL;
printf("Please enter the values of the binary tree in preorder:\n");
buildTree(&root);
printf("The result of preorder traversal with level:\n");
preorder(root, 1);
return 0;
}
```
输入格式为先序遍历,其中 `-1` 表示空节点。例如,对于如下二叉树:
```
1
/ \
2 3
/ \ \
4 5 6
```
先序遍历为 `1 2 4 -1 -1 5 -1 -1 3 -1 6 -1 -1`,则程序的输出为:
```
Please enter the values of the binary tree in preorder:
1 2 4 -1 -1 5 -1 -1 3 -1 6 -1 -1
The result of preorder traversal with level:
Level 1: 1
Level 2: 2
Level 3: 4
Level 3: 5
Level 2: 3
Level 3: 6
```
阅读全文