用C++语言写一个二叉树的基本操作代码,包括前中后遍历,层次遍历,子叶数,结点数。层次遍历使用队列
时间: 2023-06-14 10:03:57 浏览: 48
二叉树基本操作代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int value;
struct Node* left;
struct Node* right;
} Node;
// 创建节点
Node* createNode(int value) {
Node* node = (Node*)malloc(sizeof(Node));
node->value = value;
node->left = NULL;
node->right = NULL;
return node;
}
// 插入节点
Node* insert(Node* root, int value) {
if (root == NULL) {
return createNode(value);
}
if (value < root->value) {
root->left = insert(root->left, value);
} else if (value > root->value) {
root->right = insert(root->right, value);
}
return root;
}
// 前序遍历
void preOrder(Node* root) {
if (root != NULL) {
printf("%d ", root->value);
preOrder(root->left);
preOrder(root->right);
}
}
// 中序遍历
void inOrder(Node* root) {
if (root != NULL) {
inOrder(root->left);
printf("%d ", root->value);
inOrder(root->right);
}
}
// 后序遍历
void postOrder(Node* root) {
if (root != NULL) {
postOrder(root->left);
postOrder(root->right);
printf("%d ", root->value);
}
}
// 层次遍历
void levelOrder(Node* root) {
if (root == NULL) {
return;
}
Node* queue[100];
int front = 0;
int rear = 0;
queue[rear++] = root;
while (front != rear) {
Node* node = queue[front++];
printf("%d ", node->value);
if (node->left != NULL) {
queue[rear++] = node->left;
}
if (node->right != NULL) {
queue[rear++] = node->right;
}
}
}
// 计算子叶数
int leafCount(Node* root) {
if (root == NULL) {
return 0;
}
if (root->left == NULL && root->right == NULL) {
return 1;
}
return leafCount(root->left) + leafCount(root->right);
}
// 计算结点数
int nodeCount(Node* root) {
if (root == NULL) {
return 0;
}
return nodeCount(root->left) + nodeCount(root->right) + 1;
}
int main() {
Node* root = NULL;
int values[] = { 5, 2, 8, 1, 3, 7, 9 };
int n = sizeof(values) / sizeof(values[0]);
for (int i = 0; i < n; i++) {
root = insert(root, values[i]);
}
printf("前序遍历:");
preOrder(root);
printf("\n中序遍历:");
inOrder(root);
printf("\n后序遍历:");
postOrder(root);
printf("\n层次遍历:");
levelOrder(root);
printf("\n子叶数:%d", leafCount(root));
printf("\n结点数:%d", nodeCount(root));
return 0;
}
```
注意:此代码中的队列实现方式不是线程安全的,仅用于演示二叉树的层次遍历。如果需要在多线程环境中使用,请使用线程安全的队列实现。