1. 程式人生 > 實用技巧 >List Leaves(二叉樹的層序遍歷)

List Leaves(二叉樹的層序遍歷)

題目要求:按照從上至下,從左至右(層序)的順序輸出二叉樹的葉子結點。

思路:利用佇列,儲存每一個結點。

先將根入隊,然後將根出隊,訪問根結點。將根結點的兒子結點入隊,後面的結點依次執行此操作,這樣所有的結點都可以被訪問。

佇列的定義及入隊出隊操作如下:


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); } //} }