本題要求按照先序遍歷的順序輸出給定二叉樹的葉結點。
函數接口定義:
void PreorderPrintLeaves( BinTree BT );
其中BinTree
結構定義如下:
typedef struct TNode *Position;
typedef Position BinTree;
struct TNode{
ElementType Data;
BinTree Left;
BinTree Right;
};
函數PreorderPrintLeaves
應按照先序遍歷的順序輸出給定二叉樹BT
的葉結點,格式為一個空格跟着一個字符。
裁判測試程序樣例:
#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;
}
/* 你的代碼將被嵌在這里 */
輸出樣例(對於圖中給出的樹):
Leaf nodes are: D E H I
復習考研,書上只寫了中序遍歷的非遞歸算法,所以找一道題試試前序遍歷能不能寫出來。
代碼:
#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 Insert(BinTree T,ElementType X) { if(T == NULL) { T = (BinTree)malloc(sizeof(TNode)); T -> Left = T -> Right = NULL; T -> Data = X; } else if(X < T -> Data) { T -> Left = Insert(T -> Left,X); } else { T -> Right = Insert(T -> Right,X); } return T; } BinTree CreatBinTree(); void PreorderPrintLeaves( BinTree BT ); int main() { BinTree BT = CreatBinTree(); printf("Leaf nodes are:"); PreorderPrintLeaves(BT); printf("\n"); return 0; } BinTree CreatBinTree() { BinTree Bt = NULL; int n; ElementType ch; scanf("%d",&n); for(int i = 0;i < n;i ++) { getchar(); scanf("%c",&ch); Bt = Insert(Bt,ch); } return Bt; } void PreorderPrintLeaves( BinTree BT ) { BinTree b[100]; int c = 0; if(BT) b[c ++] = BT; while(c != 0) { BinTree temp = b[-- c]; if(!(temp -> Left || temp -> Right)) printf(" %c",temp -> Data); if(temp -> Right) b[c ++] = temp -> Right; if(temp -> Left) b[c ++] = temp -> Left; } }