資料結構——先序輸出葉子結點
阿新 • • 發佈:2018-11-21
保持先序遍歷不變,加一個特殊判斷是否左右節點為空即可。(注意葉子結點一定是左右孩子均為空)
下面給出AC程式碼:
#include <stdio.h> #include <stdlib.h> typedef char ElementType; typedef struct TNode *Position; typedef Position BinTree; struct TNode{ ElementType Data; BinTree Left; BinTree Right; }; BinTree CreatBinTree(); /* 實現細節忽略 */ void PreorderPrintLeaves( BinTree BT ); int main() { BinTree BT = CreatBinTree(); printf("Leaf nodes are:"); PreorderPrintLeaves(BT); printf("\n"); return 0; } void PreorderPrintLeaves( BinTree BT ) { if(BT==NULL) return; if(BT->Left==NULL&&BT->Right==NULL) { printf(" %c",BT->Data); return; } else { PreorderPrintLeaves(BT->Left); PreorderPrintLeaves(BT->Right); } }