用c++写一段代码:二叉树的四种遍历 方法
时间: 2024-05-22 16:11:58 浏览: 86
二叉树4种遍历方法的C语言实现
5星 · 资源好评率100%
#include <stdio.h>
#include <stdlib.h>
//定义二叉树结构体
typedef struct BiTreeNode {
int data;
struct BiTreeNode* left;
struct BiTreeNode* right;
} BiTreeNode, * BiTree;
//创建新结点
BiTreeNode* createNode(int data) {
BiTreeNode* node = (BiTreeNode*)malloc(sizeof(BiTreeNode));
node->data = data;
node->left = NULL;
node->right = NULL;
return node;
}
//插入结点
void insertNode(BiTree* tree, int data) {
if (*tree == NULL) {
*tree = createNode(data);
return;
}
if (data < (*tree)->data) {
insertNode(&(*tree)->left, data);
}
else if (data > (*tree)->data) {
insertNode(&(*tree)->right, data);
}
}
//前序遍历
void preorderTraversal(BiTree tree) {
if (tree == NULL) {
return;
}
printf("%d ", tree->data);
preorderTraversal(tree->left);
preorderTraversal(tree->right);
}
//中序遍历
void inorderTraversal(BiTree tree) {
if (tree == NULL) {
return;
}
inorderTraversal(tree->left);
printf("%d ", tree->data);
inorderTraversal(tree->right);
}
//后序遍历
void postorderTraversal(BiTree tree) {
if (tree == NULL) {
return;
}
postorderTraversal(tree->left);
postorderTraversal(tree->right);
printf("%d ", tree->data);
}
//层序遍历
void levelorderTraversal(BiTree tree) {
if (tree == NULL) {
return;
}
BiTreeNode* queue[1000];
int front = 0, rear = 0;
queue[rear++] = tree;
while (front < rear) {
BiTreeNode* node = queue[front++];
printf("%d ", node->data);
if (node->left != NULL) {
queue[rear++] = node->left;
}
if (node->right != NULL) {
queue[rear++] = node->right;
}
}
}
int main() {
BiTree tree = NULL;
int arr[] = { 5, 3, 7, 2, 4, 6, 8 };
int n = sizeof(arr) / sizeof(int);
for (int i = 0; i < n; i++) {
insertNode(&tree, arr[i]);
}
printf("前序遍历:");
preorderTraversal(tree);
printf("\n中序遍历:");
inorderTraversal(tree);
printf("\n后序遍历:");
postorderTraversal(tree);
printf("\n层序遍历:");
levelorderTraversal(tree);
printf("\n");
return 0;
}
阅读全文