数据结构树转换到二叉树,怎么实现前面的树,想不通,头文件不知道怎么写(语言-c++)


#include "tree.h"
#include<iostream>
using namespace std;

struct node//结构体
{
    DataType data;
    int parent;
};

node* first(int j)
{
    node* x;
    x = new node[j];
    x[0].parent = -1;

    cout << "请输入根结点值:";
    cin >> x[0].data;

    for (int i = 1; i < j; i++)
    {
        int y = 0;
        cout << "请输入第" << i << "结点值:";
        cin >> x[i].data;
        cout << "请输入它的父亲结点是:";
        cin >> y;
        x[i].parent = y;
    }
    return x;
}

void display1(node* x, int num)
{
    for (int i = 0; i < num; i++)
    {
        cout << "序号" << i << "值为" << x[i].data << "父母为" << x[i].parent << endl;
    }
}

struct nnode
{
    char data;
    nnode* left;
    nnode* right;
    nnode()
    {
        data = ' ';
        left = NULL;
        right = NULL;
    }
};

nnode* second(node* a, int num, int index)//转换二叉树
{
    nnode* root = new nnode;
    root->data = a[index].data;
    for (int i = 1; i < num; i++)
    {
        if (a[i].parent == index)
        {
            root->left = second(a, num, i);
            break;
        }
    }
    if ((index + 1) < num)
    {
        if (a[index].parent == a[index + 1].parent)
            root->right = second(a, num, index + 1);
    }
    return root;
}

void display2(nnode* x)
{
    cout << x->data << endl;
    if (x->left != NULL)
        display2(x->left);
    if (x->right != NULL)
        display2(x->right);
}

void showchild(nnode* x)//对转换的二叉树进行算法设计统计人一结点的孩子数
{
    if (x != NULL)
    {
        int num = 0;
        if (x->left != NULL)
            num++;
        if (x->right != NULL)
            num++;
        cout << "数据为" << x->data << "的节点个数为" << num << endl;
        showchild(x->left);
        showchild(x->right);
    }

}

int Max(int a, int b)
{
    if (a > b)
        return a;
    else
        return b;
}

int showheight(nnode* x)//通过递归算法求高度
{
    if (x != NULL)
    {
        return 1 + Max(showheight(x->left), showheight(x->right));
    }
    return 0;
}

void del(nnode* root)
{
    if (root == NULL)
        return;
    else {
        del(root->left);
        del(root->right);
        delete root;
    }
}


int main()
{
    int j = 0;
    cout << "请输入结点个数:" << endl;
    cin >> j;
    node* one = first(j);
    nnode* head;
    display1(one, j);
    int y = 0;
    head = second(one, j, y);
    display2(head);
    showchild(head);
    cout << "此二叉树的高度为:" << showheight(head) << endl;
    del(head);
    delete[] one;
    return 0;
}

你好,我是有问必答小助手,非常抱歉,本次您提出的有问必答问题,技术专家团超时未为您做出解答


本次提问扣除的有问必答次数,将会以问答VIP体验卡(1次有问必答机会、商城购买实体图书享受95折优惠)的形式为您补发到账户。


因为有问必答VIP体验卡有效期仅有1天,您在需要使用的时候【私信】联系我,我会为您补发。