03-树1. List Leaves (25)
03-树1. 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 N (<=10) which is the total number of nodes in the tree -- and hence the nodes are numbered from 0 to N-1. Then N 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 6Sample Output:
4 1 5
先看明白题目的意思,层次遍历用队列。但是个人觉得本题的建立二叉树过程不怎么好搞T_T,网查大侠方法看明白的。。。
#include<iostream>
#include<queue>
using namespace std;
struct TreeNode{
int Left;
int Right;
TreeNode(){
Left=-1;
Right=-1;
}
};
TreeNode node[10];
bool FindRoot[10];
int N,flag=0;
queue<int> q;
bool Isdigit(char x)
{
if((x-'0')>=0 && (x-'0')<=9){
return true;
}
else{
return false;
}
}
void BFS(int i)
{
q.push(i);
while(!q.empty()){
int t=q.front();
q.pop();
if(node[t].Left==-1 && node[t].Right==-1){
if(flag==0){
cout<<t;
flag=1;
}
else
cout<<" "<<t;
}
if(node[t].Left!=-1){
q.push(node[t].Left);
}
if(node[t].Right!=-1){
q.push(node[t].Right);
}
}
}
int main()
{
int i,j;
char left,right;
cin>>N;
for(i=0;i<sizeof(FindRoot);i++){
FindRoot[i]=false;
}
for(i=0;i<N;i++){
cin>>left>>right;
if(Isdigit(left)){
node[i].Left=left-'0';
FindRoot[node[i].Left]=1; //表明node[i].left这个数有根结点
}
if(Isdigit(right)){
node[i].Right=right-'0';
FindRoot[node[i].Right]=1;
}
}
for(i=0;i<N;i++){
if(FindRoot[i]==0){ //找出根节点
BFS(i);
break;
}
}
return 0;
}