数据结构树的双亲表示法

本文介绍了一个使用C++实现的树结构操作示例,包括初始化树、查找节点的父节点和子节点。通过输入节点个数和节点及其父节点的值,可以创建并操作树结构。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include<iostream>
#include<malloc.h>
#include<stdlib.h>
using namespace std;


#define max 100
typedef char TElemType;
typedef struct
{
    TElemType data;
    int parent;
}PTNode;

typedef struct
{
    PTNode node[max];
    int n;
}PTree;

void InitTree(PTree &tree)
{
    char ch;
    int j;
    cout << "请输入树的节点个数" << endl;
    cin >> tree.n;
    cout << "请输入结点的值和其双亲" << endl;
    for (int i = 0; i < tree.n; i++)
    {
        fflush(stdin);
        cin >> ch >> j;
        tree.node[i].data = ch;
        tree.node[i].parent = j;
    }
    tree.node[0].parent = -1;
}
void FindParent(PTree tree)
{
    int i;;
    cout << "请输入你要查找的结点" << endl;
    cin >> i;
    cout << i << "的双亲为:" << tree.node[i].parent << endl;
}

void FindChild(PTree tree)
{
    int i;
    char ch;
    //cout << "请输入你想要查找孩子的双亲的序号" << endl;
    cout << "请输入你想查找孩子双亲的值" << endl;

    cin >> ch;
    for (i = 0; i < tree.n; i++)
    {
        if (ch == tree.node[tree.node[i].parent].data)
        {
            cout << "该孩子的值为:";
            cout << tree.node[i].data << endl;
        }
        
    }
    return;

}

int main()
{
    PTree tree;
    InitTree(tree);
    //for (int i = 0; i < 10; i++)
        //FindParent(tree);
    for(int i=0;i<3;i++)
        FindChild(tree);
    return 0;
}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值