用C语言写出非递归的方法实现对给定二叉树的先序和层序遍历完整程序,并给出一组数据
时间: 2023-06-16 14:06:06 浏览: 110
以下是用C语言编写的非递归方法实现二叉树的先序和层序遍历的完整程序,以及一组测试数据:
```c
#include <stdio.h>
#include <stdlib.h>
// 二叉树节点结构体
typedef struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
// 先序遍历二叉树(非递归)
void preorderTraversal(TreeNode* root) {
if (root == NULL) {
return;
}
TreeNode* stack[100];
int top = -1;
stack[++top] = root;
while (top >= 0) {
TreeNode* node = stack[top--];
printf("%d ", node->val);
if (node->right) {
stack[++top] = node->right;
}
if (node->left) {
stack[++top] = node->left;
}
}
}
// 层序遍历二叉树(非递归)
void levelOrderTraversal(TreeNode* root) {
if (root == NULL) {
return;
}
TreeNode* queue[100];
int front = 0, rear = 0;
queue[rear++] = root;
while (front < rear) {
TreeNode* node = queue[front++];
printf("%d ", node->val);
if (node->left) {
queue[rear++] = node->left;
}
if (node->right) {
queue[rear++] = node->right;
}
}
}
// 创建二叉树(按层序遍历序列)
TreeNode* createBinaryTree(int data[], int i, int n) {
if (i >= n) {
return NULL;
}
if (data[i] == -1) {
return NULL;
}
TreeNode* root = (TreeNode*) malloc(sizeof(TreeNode));
root->val = data[i];
root->left = createBinaryTree(data, 2 * i + 1, n);
root->right = createBinaryTree(data, 2 * i + 2, n);
return root;
}
int main() {
int data[] = {1, 2, 3, 4, -1, -1, 5, -1, -1, 6};
TreeNode* root = createBinaryTree(data, 0, 10);
printf("先序遍历:");
preorderTraversal(root);
printf("\n层序遍历:");
levelOrderTraversal(root);
return 0;
}
```
测试数据:二叉树的层序遍历序列为 {1, 2, 3, 4, -1, -1, 5, -1, -1, 6},其中 -1 表示空节点。
阅读全文