简体   繁体   English

你如何制作函数来返回C中二叉树中给定级别的所有节点

[英]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.在 C 程序中返回二叉树中给定级别的节点。 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.我想更改为int NodesAtLevel(BTnode_t* root, int 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. "提示是“编写一个算法,得到一个二叉树的数字 k 并返回 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.然后在函数外部创建一个指向动态结构数组的指针,将指针传递给NodesAtLevel (您必须将其添加到函数参数列表中),并在每个新函数调用malloc一个新的并将其保存到指针中。 Then assign the values you want to return into the malloc d struct.然后将要返回的值分配到malloc d 结构中。 Then return it.然后归还。 When you are all done, free them all.全部完成后,将它们全部释放。

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

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