二叉树的基本运算及其实现 编程实现:建立二叉树并输出下列二叉树的(1)结点个数;(2)叶子结点个数;(3)深度;(4)先序序列、中序序列和后序序列。用C语言实现
时间: 2023-06-10 22:07:35 浏览: 84
以下是用 C 语言实现建立二叉树并输出相关信息的代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
char data;
struct Node* left;
struct Node* right;
} Node;
Node* createNode(char data) {
Node* node = (Node*)malloc(sizeof(Node));
node->data = data;
node->left = NULL;
node->right = NULL;
return node;
}
Node* createTree() {
Node* root = createNode('A');
root->left = createNode('B');
root->left->left = createNode('D');
root->left->right = createNode('E');
root->left->right->left = createNode('G');
root->right = createNode('C');
root->right->right = createNode('F');
return root;
}
int countNodes(Node* root) {
if (root == NULL) {
return 0;
}
return countNodes(root->left) + countNodes(root->right) + 1;
}
int countLeaves(Node* root) {
if (root == NULL) {
return 0;
}
if (root->left == NULL && root->right == NULL) {
return 1;
}
return countLeaves(root->left) + countLeaves(root->right);
}
int depth(Node* root) {
if (root == NULL) {
return 0;
}
int leftDepth = depth(root->left);
int rightDepth = depth(root->right);
return (leftDepth > rightDepth) ? (leftDepth + 1) : (rightDepth + 1);
}
void preOrder(Node* root) {
if (root != NULL) {
printf("%c ", root->data);
preOrder(root->left);
preOrder(root->right);
}
}
void inOrder(Node* root) {
if (root != NULL) {
inOrder(root->left);
printf("%c ", root->data);
inOrder(root->right);
}
}
void postOrder(Node* root) {
if (root != NULL) {
postOrder(root->left);
postOrder(root->right);
printf("%c ", root->data);
}
}
int main() {
Node* root = createTree();
printf("Number of nodes: %d\n", countNodes(root));
printf("Number of leaves: %d\n", countLeaves(root));
printf("Depth: %d\n", depth(root));
printf("Pre-order traversal: ");
preOrder(root);
printf("\n");
printf("In-order traversal: ");
inOrder(root);
printf("\n");
printf("Post-order traversal: ");
postOrder(root);
printf("\n");
return 0;
}
```
输出结果为:
```
Number of nodes: 7
Number of leaves: 3
Depth: 4
Pre-order traversal: A B D E G C F
In-order traversal: D B G E A C F
Post-order traversal: D G E B F C A
```
阅读全文