题目要求:按照从上至下,从左至右(层序)的顺序输出二叉树的叶子结点。
思路:利用队列,保存每一个结点。
先将根入队,然后将根出队,访问根结点。将根结点的儿子结点入队,后面的结点依次执行此操作,这样所有的结点都可以被访问。
队列的定义及入队出队操作如下:
typedef struct Queue* SQueue;
struct Queue { int num; SQueue next; }; int out(SQueue Q) { SQueue q = Q->next; int ret = q->num; Q->next = q->next; free(q); return ret; } void in(SQueue Q,int number) { SQueue q= (SQueue)malloc(sizeof(struct Queue)); q->num = number; q->next = NULL; if (Q->next == NULL) { Q->next = q; return; } SQueue p = Q->next; while (p->next) { p = p->next; } p->next = q; return; }
代码:
#include <stdio.h> #include <stdlib.h> #include <string.h> #define Max 10 #define Null -1 struct TreeNode { int left; int right; }T[Max]; int count = 0;//统计总叶子数 int Initial(struct TreeNode T[]); void Travel(int root); int main() { int root = Initial(T); Travel(root); return 0; } int Initial(struct TreeNode T[]) { int N; int flag[Max] = { 0 }; if(scanf("%d",&N)==1){} int i; char c1, c2; getchar(); for (i = 0;i < N;i++) { if(scanf("%c %c",&c1,&c2)==2){} getchar(); if (c1 == c2) count++; if (c1 == '-') T[i].left = Null; else { T[i].left = c1 - '0'; flag[T[i].left] = 1; } if (c2 == '-') T[i].right = Null; else { T[i].right = c2 - '0'; flag[T[i].right] = 1; } } for (i = 0;i < N;i++) {//寻找根结点 if (!flag[i]) break; } return i; } void Travel(int root) { SQueue Q = (SQueue)malloc(sizeof(struct Queue)); SQueue q = Q; SQueue m; q->next = NULL; q->num = -1; //int p = root; in(Q, root); //while (p != Null||Q->next) { while (Q->next) { int number = out(Q); if (T[number].left == Null && T[number].right == Null) { printf("%d", number); count--; if (count) printf(" "); } if (T[number].left != Null) in(Q, T[number].left); if (T[number].right != Null) in(Q, T[number].right); } //} }