【发布时间】:2021-02-26 16:11:35
【问题描述】:
我有一个创建二叉树的函数,对于树中的每个节点,我需要将一个节点添加到一个单独的链表中,该链表指向二叉树中的节点。
我创建二叉树的函数:
typedef struct myTree _node;
void INSERT(_node *(*tree), _node *item) {
if (!(*tree)) {
*tree = item;
return;
}
if (item->val < (*tree)->val) {
INSERT(&(*tree)->left, item);
}
else if (item->val > (*tree)->val) {
INSERT(&(*tree)->right);
}
}
我的主要功能:
int main(void) {
int i;
int *balanced;
_node *current, *root;
root = NULL;
for (i = 0; i < size; i++) {
current = (_node *)malloc(sizeof(_node));
current->left = current->right = NULL;
current->val = balanced[i];
INSERT(&root, current);
}
return 0;
}
为简单起见,我省略了部分主要功能。
想法是想把树的内容按pre、in、post顺序打印出来,同时遍历链表,打印每个链表节点指向的树中节点的值.
我才几个月才开始学习 C,所以我还不是很先进。
【问题讨论】:
-
虽然我还没有看过这个问题,但让我指出你的指针声明语法很奇怪。虽然将双指针声明为
int *(*foo)肯定是有效的,但大多数人会将其声明为int ** foo(或int** foo或int **foo,取决于他们的个人风格)。另外,不要使用像_node这样的带下划线前缀的类型名称,因为它们是保留的;虽然struct myTree本身就是一个非常好的类型名称,但如果您真的必须使用 typedef,请考虑使用类似node_t甚至只是Node。
标签: c loops linked-list binary-tree