给定一颗二叉树,要求输出遍历该二叉树得到的先序、中序、后序遍历序列。C语言代码
时间: 2023-07-10 14:14:04 浏览: 92
举例讲解C语言程序中对二叉树数据结构的各种遍历方式
以下是 C 语言代码实现二叉树的先序、中序、后序遍历:
```c
#include<stdio.h>
#include<stdlib.h>
struct Node {
int data;
struct Node *left;
struct Node *right;
};
struct Node* newNode(int data) {
struct Node* node = (struct Node*)malloc(sizeof(struct Node));
node->data = data;
node->left = NULL;
node->right = NULL;
return node;
}
void preOrder(struct Node* node) {
if (node == NULL) return;
printf("%d ", node->data);
preOrder(node->left);
preOrder(node->right);
}
void inOrder(struct Node* node) {
if (node == NULL) return;
inOrder(node->left);
printf("%d ", node->data);
inOrder(node->right);
}
void postOrder(struct Node* node) {
if (node == NULL) return;
postOrder(node->left);
postOrder(node->right);
printf("%d ", node->data);
}
int main() {
struct Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
printf("Preorder traversal: ");
preOrder(root);
printf("\nInorder traversal: ");
inOrder(root);
printf("\nPostorder traversal: ");
postOrder(root);
return 0;
}
```
输出结果为:
```
Preorder traversal: 1 2 4 5 3
Inorder traversal: 4 2 5 1 3
Postorder traversal: 4 5 2 3 1
```
阅读全文