题目链接:
poj 3437 Tree Grafting
题意:
给一个多叉树的序列,d表示向下加一个子节点,u表示返回上一层的父节点
问这么一个多叉树的高度转为二叉树,这个二叉树的高度有多高
转二叉树的方法题目已经告诉你了:
“左儿子,右兄弟”
就是将一个节点的第一个儿子放在左儿子的位置,下一个的儿子,即左儿子的第一个兄弟,
放在左儿子的右儿子位置上,再下一个兄弟接着放在右儿子的右儿子.

我们不难发现,对于多叉树,每d一次就是当前节点深度+1,我们只需要比较加完深度之后从这个节点到根节点的树高是不是在这个多叉树其余节点中是最高的就可以了。
对于求转完二叉树的树高,我们根据上面的转换方式可以发现,二叉树当前节点的高,即为这个节点在二叉树中的高度再加上这个节点是多叉树的父节点的第几个儿子,最后把所有的高度取最高,就是转换为二叉树之后的树高
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <string>
#include <cmath>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <stack>
#include <sstream>
using namespace std;
typedef long long ll;
const int inf = 0x3f3f3f3f;
const int maxn = 30;
int M_treehigh,B_treehigh;//多叉树深度,二叉树深度
string tree;
void Build_Tree(int &i,int blevel,int mlevel)
{
int tempson = 0;
while(tree[i] == 'd'){
i++;
tempson++;
Build_Tree(i,blevel + 1,mlevel + tempson);
}
//再回到上一层节点时要动态更新当前树的最大深度
i++;
//更新多叉树的高度
B_treehigh = max(B_treehigh,blevel);
//更新转为二叉树的高度
M_treehigh = max(M_treehigh,mlevel);
}
int main()
{
int cas = 0;
while(cin>>tree&&tree != "#"){
cas++;
int i = 0;
M_treehigh = B_treehigh = 0;
Build_Tree(i,0,0);
cout<<"Tree "<<cas<<": "<<B_treehigh<<" => "<<M_treehigh<<endl;
}
return 0;
}
本文详细解析了POJ3437 Tree Grafting问题,介绍了如何将多叉树转化为二叉树,并计算转化后的二叉树高度。通过递归构建树结构,动态更新树的最大深度,最终输出多叉树和二叉树的高度。

341

被折叠的 条评论
为什么被折叠?



