简体   繁体   English

C 中的结构调用中的结构

[英]Struct inside a struct call in C

I got this struct and I want to call it by a good way !我得到了这个结构,我想用一个好方法来调用它!

struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
};

I made this code for the call of my struct:我为调用我的结构制作了这段代码:

struct TreeNode left2 = {
            4
};
struct TreeNode right2 = {
            5
};
struct TreeNode left = {
        2,
        &left2,
        &right2         
};
struct TreeNode right = {
        3
};
struct TreeNode binary = {
    1,
    &left,
    &right

};

But that's a little bit loud, is there another way (without changing the struct), simplest, to do it?但这有点响亮,有没有另一种方法(不改变结构),最简单的方法?

You can put all the nodes into a single array (I put the root node into index#0):您可以将所有节点放入一个数组中(我将根节点放入 index#0):


struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    };

struct TreeNode all[] = {
        { 1, &all[1], &all[2]}, // Binary(root)
        { 2, &all[3], &all[4]}, // Left
        { 3, NULL, NULL},       // Right
        { 4, NULL, NULL},       // Left2
        { 5, NULL, NULL},       // Right2
        };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM