二叉树前序遍历读入和输出模板-递归算法

#include <stdio.h>
#include <string.h>
typedef struct k
{
        char data;
        struct k *left,*right;
}node;
node *Scan()
{
 node *t;
 char ch;
 if((ch=getchar())=='#')return NULL;
 t=(node *)malloc(sizeof(node));
 t->data=ch;
 t->left=Scan();
 t->right=Scan();
 return t;
}
void Print(node *head)
{
    if(head==NULL)return;
    printf("%c",head->data);
    Print(head->left);
    Print(head->right);
}
/*中序:void Print(node *head)
{
    if(head==NULL)return;
    Print(head->left);
    printf("%c",head->data);
    Print(head->right);
}*/
/*后序:void Print(node *head)
{
    if(head==NULL)return;
    Print(head->left);
    Print(head->right);
    printf("%c",head->data);
}*/
int main()
{
    node * head=Scan();
    Print(head);
return 0;
}


 

                
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面我将为您详细介绍建立二叉树并实现遍历的过程及代码注释。 1. 建立二叉树 首先,我们需要定义二叉树的结构体,包含左右子树指针和结点值。 ```c typedef struct node { int data; struct node *lchild, *rchild; } Node, *Tree; ``` 接着,我们可以通过递归的方式来构建二叉树,其中输入为当前结点的地址,输出为构建好的二叉树。 ```c Tree createTree(Tree t) { int val; scanf("%d", &val); // 读入当前结点的值 if (val == -1) // 如果当前值为-1,表示该结点为空 { t = NULL; } else { t = (Tree)malloc(sizeof(Node)); // 申请空间 t->data = val; // 存储当前结点的值 t->lchild = createTree(t->lchild); // 递归构建左子树 t->rchild = createTree(t->rchild); // 递归构建右子树 } return t; } ``` 2. 先序遍历 先序遍历是指先访问根结点,再遍历左子树,最后遍历右子树。我们可以通过递归的方式来实现先序遍历。 ```c void preOrder(Tree t) { if (t == NULL) // 如果当前结点为空,直接返回 { return; } printf("%d ", t->data); // 先访问根结点 preOrder(t->lchild); // 再遍历左子树 preOrder(t->rchild); // 最后遍历右子树 } ``` 3. 层次遍历 层次遍历是指从上到下、从左到右依次访问每一个结点。我们可以借助队列来实现层次遍历。 ```c void levelOrder(Tree t) { if (t == NULL) // 如果当前结点为空,直接返回 { return; } Queue q; // 定义队列 initQueue(&q); // 初始化队列 enQueue(&q, t); // 根结点入队列 while (!isEmpty(&q)) // 队列不为空时循环 { Tree tmp = deQueue(&q); // 取出队头元素 printf("%d ", tmp->data); // 访问队头元素 if (tmp->lchild) // 左子树不为空,左子树入队列 { enQueue(&q, tmp->lchild); } if (tmp->rchild) // 右子树不为空,右子树入队列 { enQueue(&q, tmp->rchild); } } } ``` 其中,队列的定义和相关操作如下: ```c typedef struct queue { Tree data[MAXSIZE]; int front, rear; } Queue; void initQueue(Queue *q) { q->front = q->rear = 0; } int isEmpty(Queue *q) { return q->front == q->rear; } int isFull(Queue *q) { return (q->rear + 1) % MAXSIZE == q->front; } void enQueue(Queue *q, Tree t) { if (isFull(q)) { printf("Queue is full.\n"); return; } q->data[q->rear] = t; q->rear = (q->rear + 1) % MAXSIZE; } Tree deQueue(Queue *q) { if (isEmpty(q)) { printf("Queue is empty.\n"); return NULL; } Tree t = q->data[q->front]; q->front = (q->front + 1) % MAXSIZE; return t; } ``` 这样,我们就完成了二叉树的建立和遍历

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值