[英]How do you make function that return all the nodes at given level in binary tree in C
在 C 程序中返回二叉樹中給定級別的節點。 我想出了如何打印給定級別的所有節點,但我不知道如何返回所有節點。
這是我的代碼。 我想更改為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);
}
提示是“編寫一個算法,得到一個二叉樹的數字 k 並返回 k 級的所有值。”
創建兩個變量,並將它們放在一個結構中,並將其用作返回結構的容器。
struct container
{
int a, b;
};
然后修改函數的簽名。
struct container NodesAtLevel (BTnode_t* root, int level)
然后在函數外部創建一個指向動態結構數組的指針,將指針傳遞給NodesAtLevel
(您必須將其添加到函數參數列表中),並在每個新函數調用malloc
一個新的並將其保存到指針中。 然后將要返回的值分配到malloc
d 結構中。 然后歸還。 全部完成后,將它們全部釋放。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.