1065. 树的相关操作 (模板题)

题目:
在这里插入图片描述
样例:
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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值