首页 > 解决方案 > AVL树到C中的元组

问题描述

我有一个 AVL 树,例如:

   (6,25)
   /    \
(6,12)  (9,25)

我希望将所有元素存储到一个元组中,例如:

array= [(6,12),(6,25),(9,25)]

如何用 C 语言实现它?

标签: c

解决方案


对异构数据使用结构,例如:

struct my_eth_tuple
{
    int a;
    float b;
    char s[32];
};

然后创建元组数组:

struct my_eth_tuple[3];

您也可以将其初始化为:

struct my_eth_tuple[3] = {{6, 12.0, "tuple 1"},{6, 25, "tuple 2"},{9, 25, "tuple 3"}};

如果数据是同质的,您可以使用简单的数组数组:

typedef int my_hom_tuple[2];
my_hom_tuple[3] = {{6,12},{6,25},{9,25}};

要以编程方式访问这两者,请使用标准结构或数组用法,如下例所示:

struct my_eth_tuple
{
    int a;
    float b;
    char s[32];
};
typedef int my_hom_tuple[2];
struct my_eth_tuple[3];
struct my_hom_tuple[3];

void foo(void)
{

    for (int i = 0; i < 3; i++)
    {
        my_eth_tuple[i].a = i + 1;
        my_eth_tuple[i].b = (float)i *2.0;
        my_eth_tuple[i].s[0] = '\0';
    }

    for (int i = 0; i < 3; i++)
        for (int j = 0; j < 2; j++)
        {
            my_hom_tuple[i][j] = i + 1;
            my_hom_tuple[i][j] = i * 2;
        }
    }
}

推荐阅读