03-树2 List Leaves

来源:互联网 发布:jquery数组重复元素 编辑:程序博客网 时间:2024/05/20 02:29

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

解题思路:用数组写的这个代码.(因为节点较少,递归建树可以省一次BFS),方便调试。

#include<cstdio>#include<cstring>#include<queue>using namespace std;const int maxn=2050;int T[maxn];int N,root,cnt=0,Max;int visit[12];struct tree{    char left,right; }tree[12];void BuildTree(int Root,int index){    T[index]=Root;    if(tree[Root].left=='-'&&tree[Root].right=='-'){        if(index>Max)            Max=index;//保存最大节点值,最后遍历时用        return;    }    if(tree[Root].left!='-'){        BuildTree(tree[Root].left-'0',2*index);    }    if(tree[Root].right!='-'){        BuildTree(tree[Root].right-'0',2*index+1);    }}int main(){    //freopen("input.txt","r",stdin);    memset(T,-1,sizeof(T));    scanf("%d",&N);    for(int i=0;i<N;i++){        scanf(" %c %c",&tree[i].left,&tree[i].right);//小心换行符影响,在%c前加空格        if(tree[i].left!='-'){           visit[tree[i].left-'0']=1;        }        if(tree[i].right!='-'){           visit[tree[i].right-'0']=1;        }    }    for(int i=0;i<N;i++){        if(!visit[i]){            root=i;            break;        }    }    BuildTree(root,1);//递归建树    //BFS(root);    for(int i=1;i<=Max;i++){        if(T[i]!=-1&&T[2*i]==-1&&T[2*i+1]==-1){            if(!cnt){                printf("%d",T[i]);                cnt++;            }            else{                printf(" %d",T[i]);            }        }    }    printf("\n");    return 0;}
0 0
原创粉丝点击