C 语言中的树遍历
遍历是访问树中所有节点并打印其值的过程。由于所有节点都通过边(链接)连接,因此我们始终从根节点(头节点)开始。也就是说,我们无法随机访问树中的节点。遍历树有三种方法 −
- 中序遍历
- 前序遍历
- 后序遍历
现在我们将使用以下二叉树 − 来研究 C 语言中树遍历的实现。
C 语言实现
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node *leftChild;
struct node *rightChild;
};
struct node *root = NULL;
void insert(int data) {
struct node *tempNode = (struct node*) malloc(sizeof(struct node));
struct node *current;
struct node *parent;
tempNode->data = data;
tempNode->leftChild = NULL;
tempNode->rightChild = NULL;
//如果树为空
if(root == NULL) {
root = tempNode;
} else {
current = root;
parent = NULL;
while(1) {
parent = current;
//去树的左边
if(data < parent->data) {
current = current->leftChild;
//向左插入
if(current == NULL) {
parent->leftChild = tempNode;
return;
}
} //去树的右边
else {
current = current->rightChild;
//插入到右侧
if(current == NULL) {
parent->rightChild = tempNode;
return;
}
}
}
}
}
struct node* search(int data) {
struct node *current = root;
printf("Visiting elements: ");
while(current->data != data) {
if(current != NULL)
printf("%d ",current->data);
//转到左边的树
if(current->data > data) {
current = current->leftChild;
}
//否则转到右树
else {
current = current->rightChild;
}
//not found
if(current == NULL) {
return NULL;
}
}
return current;
}
void pre_order_traversal(struct node* root) {
if(root != NULL) {
printf("%d ",root->data);
pre_order_traversal(root->leftChild);
pre_order_traversal(root->rightChild);
}
}
void inorder_traversal(struct node* root) {
if(root != NULL) {
inorder_traversal(root->leftChild);
printf("%d ",root->data);
inorder_traversal(root->rightChild);
}
}
void post_order_traversal(struct node* root) {
if(root != NULL) {
post_order_traversal(root->leftChild);
post_order_traversal(root->rightChild);
printf("%d ", root->data);
}
}
int main() {
int i;
int array[7] = { 27, 14, 35, 10, 19, 31, 42 };
for(i = 0; i < 7; i++)
insert(array[i]);
i = 31;
struct node * temp = search(i);
if(temp != NULL) {
printf("[%d] Element found.", temp->data);
printf("
");
}else {
printf("[ x ] Element not found (%d).
", i);
}
i = 15;
temp = search(i);
if(temp != NULL) {
printf("[%d] Element found.", temp->data);
printf("
");
}else {
printf("[ x ] Element not found (%d).
", i);
}
printf("
Preorder traversal: ");
pre_order_traversal(root);
printf("
Inorder traversal: ");
inorder_traversal(root);
printf("
Post order traversal: ");
post_order_traversal(root);
return 0;
}
如果我们编译并运行上述程序,它将产生以下结果 −
输出
Visiting elements: 27 35 [31] Element found. Visiting elements: 27 14 19 [ x ] Element not found (15). Preorder traversal: 27 14 10 19 35 31 42 Inorder traversal: 10 14 19 27 31 35 42 Post order traversal: 10 19 14 31 42 35 27

tree_data_structure.html