题目 使用左孩子右兄弟结构
自上而下输入树中每条边,建立树的孩子兄弟链表存储结构,求树的深度(根的深度为1)。
例如,对如下所示的树,输入为#a,ab,ac,ad,ce,##,其中#a表示树的根是a,##表示输入结束。
a
/ | \
b c d
|
e
输入格式: 共一行连续字符序列,第1个是#字符,第2个是树的根(##表示空树);接下来自上向下、自左向右的顺序给出xy,x是y的双亲结点;最后是两个#字符,表示输入结束。结点的取值是a~z单个字符,不重复。
输出格式:输出树的深度x,x是一个整数。
示例输入:
#aabacadce##
示例输出:
3
#include <iostream>
#include <string>
using namespace std;
struct Node
{
char ch;
Node* firstchild;
Node* nextsibling;
};
Node* newNode(char ch)
{
Node* node = new Node;
node->ch = ch;
node->firstchild = NULL;
node->nextsibling = NULL;
return node;
}
void insert_Tree(Node* root,char parent,char child)
{
if(root == NULL)
{
return;
}
if(root->ch == parent)
{
if(root->firstchild == NULL)
{
root->firstchild = newNode(child);
return;
}
else
{
Node* p = root->firstchild;
while(p->nextsibling != NULL)
{
p = p->nextsibling;
}
p->nextsibling = newNode(child);
return;
}
}
else
{
insert_Tree(root->firstchild,parent,child);
insert_Tree(root->nextsibling,parent,child);
}
}
Node* CreateTree(string str)
{
Node* root = NULL;
string sub_str;
int s = 0;
while(1)
{
sub_str = str.substr(s,2);
s += 2;
if(sub_str == "##")
{
break;
}
else if(sub_str[0] == '#')
{
root = newNode(sub_str[1]);
}
else
{
insert_Tree(root,sub_str[0],sub_str[1]);
}
}
return root;
}
int depth(Node* root)
{
int m = 0;
if(root == NULL)
{
return 0;
}
else
{
Node* p = root->firstchild;
if( p == NULL)
{
return 1;
}
else
{
while(p != NULL)
{
if(depth(p) > m)
{
m = depth(p);
}
p = p->nextsibling;
}
return 1 + m;
}
}
}
int main()
{
string str;
Node* root;
cin>>str;
root = CreateTree(str);
cout<<depth(root);
return 0;
}
来自我亲爱的女朋友LJQ