[英]C Binary search tree insert not printing
我有以下二進制搜索樹代碼:編輯:更改代碼以使用指針代替值。
#include <stdio.h>
#include <stdlib.h>
typedef struct BST BST;
struct BST {
int data;
struct BST* left;
struct BST* right;
};
BST* bst = NULL;
void insert(BST *node, int num) {
BST *tmp;
if ((*node) == NULL){
tmp = (BST*) malloc(sizeof(tmp));
tmp->data = num;
tmp->left = NULL;
tmp->right = NULL;
node = tmp;
}
else if (num < (*node)->left){
insert((*node)->left, num);
}
else if (num >(*node)->right){
insert((*node)->right);
}
return;
}
void search(BST *node, int num) {
int depth = 0;
if ((*node) == NULL){
printf("Element not found");
}
else if (num = (*node)->data){
printf("Depth of element in tree: %d\n", depth);
}
else if (num < (*node)->left){
depth++;
search((*node)->left, num);
}
else if (num >(*node)->right){
depth++;
search((*node)->right);
}
else
return;
}
// Printing the elements of the tree - inorder traversal
void print(BST* bst) {
if (bst == NULL) return;
print(bst->left);
printf("%d\n", bst->data);
print(bst->right);
return;
}
int main() {
struct node* root = NULL;
insert(root, 4);
insert(root, 2);
insert(root, 1);
insert(root, 3);
insert(root, 6);
insert(root, 5);
return 0;
}
當我運行並編譯此代碼時,沒有任何答案,但也沒有輸出任何內容。 這是我必須要做的工作的一部分。 給了我print()方法,所以我應該如何改變它。 我猜想這與我負責實現的insert方法有關。 為什么沒有生產任何這樣的原因?
我在想,也許這與我最初設置為NULL的BST* bst
點有關。 我覺得我從不做任何事情,但是我不確定我該做什么。
我是C語言的新手,所以我可能錯過了一些東西。
您的代碼有很多問題。 讓我們從頂部開始(附近),然后逐步進行。
BST* bst = NULL;
盡管並不完全有害於執行,但是您根本不會使用它。
void insert(BST *node, int num) {
如果希望insert
能夠更改根指針,則需要傳遞根指針的地址,這意味着insert
將需要接收一個指向BST的指針,因此這將變為void insert(BST **node, int num)
。
if ((*node) == NULL){
實際上,這寫起來好像是上面的更改已經發生一樣-它正在嘗試取消引用node
,然后將結果與NULL
進行比較,這僅在*node
是指針的情況下才有意義(這要求該node
是指向指針的指針)。
tmp = (BST*) malloc(sizeof(tmp));
我建議不要強制轉換malloc
的返回值。 如果/忘記了#include <stdlib.h>
,這樣做可以/將阻止編譯器警告您,以便知道它返回void *
。
我將跳過一些:
void search(BST *node, int num) {
int depth = 0;
在定義和增加depth
,您實際上從未使用過它。
然后,至少有一個非常明顯的原因,您從未看到任何輸出:
int main() {
struct node* root = NULL;
insert(root, 4);
insert(root, 2);
insert(root, 1);
insert(root, 3);
insert(root, 6);
insert(root, 5);
return 0;
}
盡管您已經定義了print
來打印出樹中的項目,但是您從未真正調用它! 當然,如果更改insert
以將指針指向指針,則需要更改這些調用以傳遞root
的地址,例如: insert(&root, 4);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.