顺序存储
#include <stdio.h>// 先序遍历 (根-左-右)
void preOrder(char tree[], int i, int size) {if (i < size && tree[i] != '\0') {printf("%c ", tree[i]); // 访问根节点preOrder(tree, 2 * i, size); // 访问左子树preOrder(tree, 2 * i + 1, size); // 访问右子树}
}// 中序遍历 (左-根-右)
void inOrder(char tree[], int i, int size) {if (i < size && tree[i] != '\0') {inOrder(tree, 2 * i, size); // 访问左子树printf("%c ", tree[i]); // 访问根节点inOrder(tree, 2 * i + 1, size); // 访问右子树}
}// 后序遍历 (左-右-根)
void postOrder(char tree[], int i, int size) {if (i < size && tree[i] != '\0') {postOrder(tree, 2 * i, size); // 访问左子树postOrder(tree, 2 * i + 1, size); // 访问右子树printf("%c ", tree[i]); // 访问根节点}
}int main() {// 假设二叉树的顺序存储,索引从1开始char tree[] = { '\0', 'A', 'B', 'C', 'D', 'E', 'F', 'G' };int size = sizeof(tree) / sizeof(tree[0]);printf("先序遍历: ");preOrder(tree, 1, size);printf("\n");printf("中序遍历: ");inOrder(tree, 1, size);printf("\n");printf("后序遍历: ");postOrder(tree, 1, size);printf("\n");return 0;
}
链式存储
#include <stdio.h>
#include <stdlib.h>typedef struct TreeNode {char data; // 数据域struct TreeNode* left; // 左子节点指针struct TreeNode* right; // 右子节点指针
} TreeNode;TreeNode* createNode(char data) {TreeNode* node = (TreeNode*)malloc(sizeof(TreeNode));node->data = data;node->left = NULL;node->right = NULL;return node;
}//先序
void preOrder(TreeNode* root) {if (root != NULL) {printf("%c ", root->data); // 访问根节点preOrder(root->left); // 访问左子树preOrder(root->right); // 访问右子树}
}//中序
void inOrder(TreeNode* root) {if (root != NULL) {inOrder(root->left); // 访问左子树printf("%c ", root->data); // 访问根节点inOrder(root->right); // 访问右子树}
}//后序
void postOrder(TreeNode* root) {if (root != NULL) {postOrder(root->left); // 访问左子树postOrder(root->right); // 访问右子树printf("%c ", root->data); // 访问根节点}
}int main() {// 创建二叉树节点TreeNode* root = createNode('A');root->left = createNode('B');root->right = createNode('C');root->left->left = createNode('D');root->left->right = createNode('E');root->right->left = createNode('F');root->right->right = createNode('G');// 先序遍历printf("先序遍历: ");preOrder(root);printf("\n");// 中序遍历printf("中序遍历: ");inOrder(root);printf("\n");// 后序遍历printf("后序遍历: ");postOrder(root);printf("\n");return 0;
}