数据结构中数的父亲表示法

#include<stdio.h>

typedef struct TreeNode
{
    int date;//树中的数据
    int parent;//父亲节点在数组中的下标
}Node;

//结构体数组
Node* node[5];
int size;//当前元素个数
int maxSize;//当前最大元素个数

//初始化   后面区分跟和树杈
void Init()
{
    size = 0;
    maxSize = 5;

}
//参数为根节点的值
void insert_root(int key)
{
    Node* new_node = (Node*)malloc(sizeof(Node));
    new_node->date = key;
    new_node->parent = -1;//跟节点的索引,变相的指针
    node[size] = new_node;//将根节点存储到所建立的结构体数组中
    size++;
}
//查找有无节点     key待查的值
int find_parent(int key)
{
    for (int i = 0; i <= size; i++)
    {
        if (key == node[i]->date)
        {
            return i;
        }
    }
    return -1;
}
void insert_child(int key, int parent_node)
{
    if (size == maxSize)
    {
        //元素满了  提示或扩容
    }
    else
    {
        //1.参数是否正确   父节点的有无
        int parent_index = find_parent(parent_node);
        if (parent_index == -1)
        {
            //给个提示 跳出函数
        }
        else
        {
            Node* new_node = (Node*)malloc(sizeof(Node));
            new_node->date = key;
            new_node->parent = parent_index;//跟节点的索引,变相的指针
            node[size] = new_node;//将根节点存储到所建立的结构体数组中
            size++;
        }
    }
}
int main()
{
    Init();
    insert_root(5);
    insert_child(4, 5);
    insert_child(3, 4);
    printf("%d-----%d", node[2]->date, node[2]->parent//其父亲的指针  索引);//node[node[2].parent]->date表示为所指的他的父亲的数据
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值