題目描述
對於給定的二叉樹,本題要求你按從上到下、從左到右的順序輸出其所有葉節點。
輸入格式:
首先第一行給出一個正整數 N(≤10),爲樹中結點總數。樹中的結點從 0 到 N−1 編號。隨後 N 行,每行給出一個對應結點左右孩子的編號。如果某個孩子不存在,則在對應位置給出 “-”。編號間以 1 個空格分隔。
輸出格式:
在一行中按規定順序輸出葉節點的編號。編號間以 1 個空格分隔,行首尾不得有多餘空格。
輸入樣例:
8
1 -
- -
0 -
2 7
- -
- -
5 -
4 6
輸出樣例:
4 1 5
思路分析
先找到父節點,父節點一定不是任何節點的子節點。找到父節點後,根據他的左右子樹創建樹。
設計一個結構體,可以存當前節點和左右節點。任何定義一個結構體數組,當找到根節點後,遞歸傳入左右子樹根的下標和數組即可。
源代碼
#include<stdio.h>
#include<stdlib.h>
typedef struct Node *node;
struct Node {//儲存輸入數據,並找到父節點
int on;
int left;
int right;
};
typedef struct Snode *Tree;
struct Snode{//樹
int data;
Tree Left;
Tree Right;
};
int flag=1;//判斷輸出時第一個字母不帶空格
Tree buidTree(int rot,node nod[]);
void myprint(Tree t);
int main(){
int n,j=0,num[14]={0};
node tr[14];
char ch;
scanf("%d",&n);
scanf("%c",&ch);//清除回車
char str[5];
//輸入數據,沒有孩子的默認爲1
for(int i=0;i<n;i++){
node t=(node)malloc(sizeof(struct Node));
gets(str);
if(str[0]!='-'){t->left=(int)(str[0]-'0');num[t->left]++;}
else t->left=-1;
if(str[2]!='-'){t->right=str[2]-'0';num[t->right]++;}
else t->right=-1;
t->on=i;//記住父節點值
tr[i]=t;
}
//找根結點
for(j;j<n;j++)
if(num[j]==0)
break;
Tree T=buidTree(j,tr);
myprint(T);
}
//層序輸出
void myprint(Tree t){
int first=0;
Tree tep;
Tree dd[12];
int top=0,dom=0;//
dd[top]=t;//借數組當隊列用
top++;
while(dom<top){
tep=dd[dom];//出隊
dom++;
if(!tep->Left&&!tep->Right){
first++;
if(first==flag)printf("%d",tep->data);
else printf(" %d",tep->data);
}
if(tep->Left){ dd[top]=tep->Left;top++;}//入隊
if(tep->Right) {dd[top]=tep->Right;top++;}
}
}
Tree buidTree(int rot,node nod[]){
node t= nod[rot];
Tree tr=(Tree)malloc(sizeof(struct Snode));
tr->data=t->on;
if(t->left!=-1){
tr->Left=buidTree(t->left,nod);
}else tr->Left=NULL;
if(t->right!=-1){
tr->Right=buidTree(t->right,nod);
}else tr->Right=NULL;
return tr;
}