简体   繁体   中英

How do you make function that return all the nodes at given level in binary tree in C

Returning the nodes at given level in a binary tree in C program. I figured out how print all the nodes at given level, but I don't know how to return all the nodes.

This is my code. I want to change to int NodesAtLevel(BTnode_t* root, int level) and then return all the nodes at given level.

void NodesAtLevel(BTnode_t* root, int level) {
    if (root == NULL) {
        return;   
    }  

    if (level == 0) {
        printf(" %d ", root->value);
        return;
    }
  
    NodesAtLevel(root->left, level - 1);
    NodesAtLevel(root->right, level - 1);
}

The prompt is "Write an algorithm that gets a Binary Tree a number k and returns all values in level k. "

Make two variables, and put them inside a struct, and use that as you container for returning structs.

struct container
{
    int a, b;
};

Then modify the function's signature.

struct container NodesAtLevel (BTnode_t* root, int level)

Then create a pointer to an dynamic array of struct outside the function, pass the pointer to NodesAtLevel (you will have to add it to the function parameter list) and at each new function call malloc a new one and save it into the pointer. Then assign the values you want to return into the malloc d struct. Then return it. When you are all done, free them all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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