建立多叉树树 和求树的深度

题目 使用左孩子右兄弟结构
在这里插入图片描述

自上而下输入树中每条边,建立树的孩子兄弟链表存储结构,求树的深度(根的深度为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
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值