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 6
Sample Output:
4 1 5
算法思路:简单的层序遍历,不过只输出叶子结点。
#include<bits/stdc++.h>
using namespace std;
struct TreeNode{
int data;
TreeNode *left;
TreeNode *right;
TreeNode(int x):data(x),left(NULL),right(NULL){}
};
void getLeaves(TreeNode* root,int m){
queue<TreeNode*> q;
q.push(root);
TreeNode* node;
while(!q.empty()){
node=q.front();
q.pop();
if(!node->left && !node->right){
cout<<node->data;
if(m){
cout<<" ";
m--;
}
continue;
}
if(node->left){
q.push(node->left);
}
if(node->right){
q.push(node->right);
}
}
cout<<endl;
}
TreeNode* buildTree(const int& n,int& countLeaves){
vector<TreeNode*> vec;
for(int i=0;i<n;i++){
TreeNode *node=new TreeNode(i);
vec.push_back(node);
}
vector<int> memo(n,0);
char l,r;
int le,ri;
for(int i=0;i<n;i++){
cin>>l>>r;
if(l=='-' && r=='-'){
countLeaves++;
continue;
}
if(l!='-'){
le=l-'0';
vec[i]->left=vec[le];
memo[le]=1;
}
if(r!='-'){
ri=r-'0';
vec[i]->right=vec[ri];
memo[ri]=1;
}
}
int headNum=0;
for(headNum=0;headNum<n;headNum++) if(memo[headNum]==0) break;
return vec[headNum];
}
int main(){
int n;
cin>>n;
int countLeaves=0;
TreeNode *root=buildTree(n,countLeaves);
getLeaves(root,countLeaves-1);
return 0;
}