树的转换

本文介绍了一种将一般树转换为二叉树的方法——左儿子右兄弟法,并通过示例详细解析了如何利用该方法进行转换,同时计算转换前后树的高度。

7:树的转换

总时间限制: 
5000ms 
内存限制: 
65536kB
描述

我们都知道用“左儿子右兄弟”的方法可以将一棵一般的树转换为二叉树,如:

    0                             0
  / | \                          /
 1  2  3       ===>             1
   / \                           \
  4   5                           2
                                 / \
                                4   3
                                 \
                                  5

现在请你将一些一般的树用这种方法转换为二叉树,并输出转换前和转换后树的高度。

输入
输入包括多行,最后一行以一个#表示结束。
每行是一个由“u”和“d”组成的字符串,表示一棵树的深度优先搜索信息。比如,dudduduudu可以用来表示上文中的左树,因为搜索过程为:0 Down to 1 Up to 0 Down to 2 Down to 4 Up to 2 Down to 5 Up to 2 Up to 0 Down to 3 Up to 0。
你可以认为每棵树的结点数至少为2,并且不超过10000。
输出
对于每棵树,按如下格式输出转换前和转换后树的高度:
Tree t: h1 => h2
其中t是树的编号(从1开始),h1是转换前树的高度,h2是转换后树的高度。
样例输入
dudduduudu
ddddduuuuu
dddduduuuu
dddduuduuu
#
样例输出
Tree 1: 2 => 4
Tree 2: 5 => 5
Tree 3: 4 => 5
Tree 4: 4 => 4
  • #include<iostream>
    #include<cmath>
    #include<cstring>
    #include<algorithm>
    #include<iomanip>
    #include<queue>
    #include<stack>
    #include<vector>
    #include<set>
    #include<map>
    using namespace std;
    struct Node
    {
    	vector<int>Son;
    	int father;
    	int depth;
    }N[10005];
    string s;
    int num=0,len=0,h1,h2;
    void MakeTree(int father,int x)
    {
    	if(x>=len)return;
    	if(s[x]=='d')
    	{
    		N[num].depth=N[father].depth+1;
    		N[num].father=father;
    		N[father].Son.push_back(num);
    		if(h1<N[num].depth)h1=N[num].depth;
    		num++;
    		MakeTree(num-1,x+1);
    	}
    	else
    	{
    		MakeTree(N[father].father,x+1);
    	}
    }
    void Search(int father,int x,int depth)
    {
    	int n=N[father].Son.size();	
    	if(x>=n)return;
    	if(h2<depth)h2=depth;
    	Search(father,x+1,depth+1);
    	Search(N[father].Son[x],0,depth+1);
    }
    void Init(int root)
    {
    	int n=N[root].Son.size();
    	for(int i=0;i<n;++i)
    	{
    		Init(N[root].Son[i]);
    	}
    	N[root].father=0;
    	N[root].depth=0;
    	N[root].Son.clear();
    }
    int main()
    {
    	int Test=0;
    	while(cin>>s)
    	{
    	    len=s.length(),h1=0,h2=0;
    		if(s[0]=='#')
    		{
    			break;
    		}
    		Test++;
    		Init(0);
    		num=1;
    		MakeTree(0,0);
    		Search(0,0,1);
    		cout<<"Tree "<<Test<<": "<<h1<<" => "<<h2<<endl;
    	}
    	return 0;
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值