题目:
样例:
input:
1 -1
2 1
3 2
4 3
5 4
6 5
7 5
8 6
9 7
10 7
11 8
12 9
13 9
14 10
15 10
output:
1 2 3 4 5 6 8 11 7 9 12 13 10 14 15
11 8 6 12 13 9 14 15 10 7 5 4 3 2 1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
15
11 12 13 14 15
5
7
思路:
#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
#define maxn 1111
using namespace std;
int idex,parent;
int cntl=0;
struct Node
{
int data;int parent;vector<int> child;
}a[maxn];
void preorder(Node* a,int root)
{
//cout<<"!!!"<<endl;cout<<root<<" ";for(int i=0;i<a[root].child.size();i++){
preorder(a,a[root].child[i]);}
}
void postorder(Node* a,int root)
{
for(int i=0;i<a[root].child.size();i++){
postorder(a,a[root].child[i]);}cout<<root<<" ";
}
void levelroder(Node* a,int root)
{
Node q[maxn],p;int head=1,tail=2;if(a==nullptr) return;for(int i=1;i<=idex;i++) q[i]=a[i];while(head<tail){
p=q[head++];cout<<p.data<<" ";for(int i=0;i<p.child.size();i++){
q[tail++]=a[p.child[i]];}}
}
void getLeaf(Node *a,int root)
{
if(a[root].child.size()==0)//判断是否是叶子节点{
cntl++;cout<<root<<" ";return;}for(int i=0;i<a[root].child.size();i++){
getLeaf(a,a[root].child[i]);}
}
int getHeight(Node *a,int root)
{
if(a[root].child.size()==0) return 0;else{
int maxH=0;for(int i=0;i<a[root].child.size();i++)//从高度为1的那一层开始往下数有几层{
int height=getHeight(a,a[root].child[i]);if(height>maxH) maxH=height;//取最大}return maxH+1;//加上根节点下面的那层}
}
int main()
{
while(cin>>idex>>parent){
a[idex].data=idex;a[idex].parent=parent;//cout<<idex<<" "<<parent<<endl;}int root=0;for(int i=1;i<=idex;i++){
if(a[i].parent==-1) root=i;else a[a[i].parent].child.push_back(i);//cout<<a[i].data<<" "a[i].parent;}preorder(a,root);cout<<endl;postorder(a,root);cout<<endl;levelroder(a,root);cout<<endl;cout<<idex<<endl;getLeaf(a,root);cout<<endl;cout<<cntl<<endl;cout<<getHeight(a,root)<<endl;return 0;
}