52 lines
1.5 KiB
C
52 lines
1.5 KiB
C
|
|
#include <stdio.h>
|
||
|
|
#include <stdlib.h>
|
||
|
|
typedef struct TreeNode {
|
||
|
|
int val;
|
||
|
|
struct TreeNode *left;
|
||
|
|
struct TreeNode *right;
|
||
|
|
} TreeNode;
|
||
|
|
TreeNode* createNode(int value) {// 创建新节点
|
||
|
|
TreeNode *newNode = (TreeNode*)malloc(sizeof(TreeNode));
|
||
|
|
newNode->val = value;
|
||
|
|
newNode->left = NULL;
|
||
|
|
newNode->right = NULL;
|
||
|
|
return newNode;
|
||
|
|
}
|
||
|
|
void preorderTraversal(TreeNode *root) {
|
||
|
|
if (root == NULL) return;
|
||
|
|
printf("%d ", root->val); // 访问根节点
|
||
|
|
preorderTraversal(root->left); // 遍历左子树
|
||
|
|
preorderTraversal(root->right); // 遍历右子树
|
||
|
|
}
|
||
|
|
void inorderTraversal(TreeNode *root) {
|
||
|
|
if (root == NULL) return;
|
||
|
|
inorderTraversal(root->left); // 遍历左子树
|
||
|
|
printf("%d ", root->val); // 访问根节点
|
||
|
|
inorderTraversal(root->right); // 遍历右子树
|
||
|
|
}
|
||
|
|
void postorderTraversal(TreeNode *root) {
|
||
|
|
if (root == NULL) return;
|
||
|
|
postorderTraversal(root->left); // 遍历左子树
|
||
|
|
postorderTraversal(root->right); // 遍历右子树
|
||
|
|
printf("%d ", root->val); // 访问根节点
|
||
|
|
}
|
||
|
|
int main() {
|
||
|
|
// 创建二叉树
|
||
|
|
TreeNode *root = createNode(1);
|
||
|
|
root->left = createNode(2);
|
||
|
|
root->right = createNode(3);
|
||
|
|
root->left->left = createNode(4);
|
||
|
|
root->left->right = createNode(5);
|
||
|
|
|
||
|
|
printf("前序遍历: ");
|
||
|
|
preorderTraversal(root);
|
||
|
|
printf("\n");
|
||
|
|
printf("中序遍历: ");
|
||
|
|
inorderTraversal(root);
|
||
|
|
printf("\n");
|
||
|
|
printf("后序遍历: ");
|
||
|
|
postorderTraversal(root);
|
||
|
|
printf("\n");
|
||
|
|
return 0;
|
||
|
|
}
|