C#关于二叉树的遍历:前序。中序。后序

 

``` #include <stdio.h> #include <stdlib.h> //定义二叉树结构体 typedef struct TreeNode { char data; struct TreeNode* left; struct TreeNode* right; } TreeNode; //前序遍历 void preOrder(TreeNode* root) { if (root == NULL) { return; } printf("%c ", root->data); preOrder(root->left); preOrder(root->right); } //中序遍历 void inOrder(TreeNode* root) { if (root == NULL) { return; } inOrder(root->left); printf("%c ", root->data); inOrder(root->right); } //后序遍历 void postOrder(TreeNode* root) { if (root == NULL) { return; } postOrder(root->left); postOrder(root->right); printf("%c ", root->data); } //层次遍历 void levelOrder(TreeNode* root) { if (root == NULL) { return; } TreeNode* queue[100]; int front = 0; int rear = 0; queue[rear++] = root; while (front != rear) { TreeNode* node = queue[front++]; printf("%c ", node->data); if (node->left != NULL) { queue[rear++] = node->left; } if (node->right != NULL) { queue[rear++] = node->right; } } } //创建二叉树 TreeNode* createTree() { char ch; scanf("%c", &ch); if (ch == '#') { return NULL; } TreeNode* node = (TreeNode*)malloc(sizeof(TreeNode)); node->data = ch; node->left = createTree(); node->right = createTree(); return node; } int main() { printf("请输入二叉树前序遍历序列:\n"); TreeNode* root = createTree(); printf("前序遍历序列为:"); preOrder(root); printf("\n中序遍历序列为:"); inOrder(root); printf("\n后序遍历序列为:"); postOrder(root); printf("\n层次遍历序列为:"); levelOrder(root); printf("\n"); return 0; } ``` 其中,`#`表示空节点,例如一个二叉树前序序列为`AB##C##`,则表示这颗二叉树的结构如下: ``` A / \ B C / \ / \ # # # # ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值