[pta] 03 - 나무 2 List Leaves (25 점)

7696 단어 pta데이터 구조
03 - 나무 2 List Leaves (25 점)
Given a tree, you are supposed to list all the leaves in the order of top down, and left to right.
Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer NN (\le 10≤10) which is the total number of nodes in the tree – and hence the nodes are numbered from 0 to N-1N−1. Then NN lines follow, each corresponds to a node, and gives the indices of the left and right children of the node. If the child does not exist, a “-” will be put at the position. Any pair of children are separated by a space.
Output Specification:
For each test case, print in one line all the leaves’ indices in the order of top down, and left to right. There must be exactly one space between any adjacent numbers, and no extra space at the end of the line.
Sample Input:
8 1 - - - 0 - 2 7 - - - - 5 - 4 6
Sample Output:
4 1 5
층 차 를 옮 겨 다 니 는 방법 을 사용 하 다.
#include
#include

#define MaxTree 10
#define ElementType int
#define Tree int
#define Null -1

struct TreeNode{
    ElementType Element;
    Tree Left;
    Tree Right;
}T[MaxTree];

int BuildTree(){
    int i,N;
    char cl,cr;
    //printf("enter N:");
    scanf("%d",&N);
    InitializeTree(N);
    ReadTree(N);
    return N;
    //initial Tree
}

void InitializeTree(int N){
    struct TreeNode *TreePointer;
    for(int i=0;iElement=i;
        TreePointer->Left=-1;
        TreePointer->Right=-1;
        //printf("e:%d l:%d r:%d
"
,TreePointer->Element,TreePointer->Left,TreePointer->Right); } } //read Tree void ReadTree(int N){ char cl,cr; int i; struct TreeNode *TreePointer; for(i=0;i//printf("enter[%d] left & right :",i); scanf(" %c",&cl); scanf(" %c",&cr); if(cl!='-'){ TreePointer->Left=cl-'0'; } if(cr!='-'){ TreePointer->Right=cr-'0'; } } return 0; } void PrintTree(int N){ for(int i=0;iprintf("e:%d l:%d r:%d
"
,T[i].Element,T[i].Left,T[i].Right); } int findRoot(int N){ int i,j,root; root = 0; for(i=0;ifor(j=0;j//printf("T[%d].Left:%d T[%d].Right:%d T[%d].Element:%d
"
,j,T[j].Left,j,T[j].Right,root,T[root].Element); if(T[j].Left==T[root].Element||T[j].Right==T[root].Element){ //printf("root changed"); root = j; break; } } } return root; } void Leaves(int N,int root){ int a[N],i,j=0; a[0]=root; int flag=0; for(int i=0;i//printf("a[%d] :%d
"
,i,a[i]); //printf("e:%d l:%d r:%d
"
,T[a[i]].Element,T[a[i]].Left,T[a[i]].Right); if(T[a[i]].Left!=-1){ j++; a[j]=T[a[i]].Left; } if(T[a[i]].Right!=-1){ j++; a[j]=T[a[i]].Right; } if(T[a[i]].Left==-1&&T[a[i]].Right==-1){ if(flag==0){ printf("%d",a[i]); flag=1; }else printf(" %d",a[i]); } } } int main(){ int root,N; N = BuildTree(&T); //PrintTree(N); root=findRoot(N); //printf("root:%d
"
,root); Leaves(N,root); system("pause"); return 0; }

좋은 웹페이지 즐겨찾기