我用於打印樹的顯示函數似乎只打印第一個元素,而不是其他的。我不知道爲什麼我懷疑我沒有遞歸的插入函數可能是原因,但似乎無法理解它出錯的地方。任何有關如何糾正或代碼失敗的解釋都會有所幫助。謝謝。這棵樹顯示函數爲什麼只打印第一個元素?
#include <stdio.h>
#include<stdlib.h>
void insert(int data_add,struct tree *temp);
void display(struct tree *temp);
struct tree
{
int data;
struct tree *left;
struct tree *right;
} *root = NULL;
int main()
{
int data_add,n;
while(1)
{
printf("\n\n1.Add\n2.Display\n4.Exit\n");
scanf("%d",&n);
switch(n)
{
case 1: printf("\nEnter the element to add ");
scanf("%d",&data_add);
insert(data_add,root);
break;
case 2: printf("The nos are: ");
display(root);
break;
/*case 3: printf("The nos are: ");
reversedisplay(root);*/
case 4: exit(1);
break;
default: printf("\nChoose a appropriate option");
}
}
}
void insert(int data,struct tree *temp)
{
struct tree *current;
current = (struct tree*) malloc(sizeof(struct tree));
current->data = data;
if(root == NULL)
{
root = current;
current->left = NULL;
current->right = NULL;
}
else
{
while(temp!=NULL)
{
if(data<temp->data)
{
temp = temp->left;
}
else
{
temp = temp->right;
}
}
temp = current;
current->left = NULL;
current->right = NULL;
}
}
void display(struct tree *temp)
{
if(temp == NULL)
return;
display(temp->right);
display(temp->left);
printf("%d",temp->data);
}
問題是,插入一個元素時,您不是將新插入的元素分配爲任何其他節點的左側或右側子元素。每次嘗試插入元素時,您只是在插入時遍歷樹,因爲新元素未添加到樹中。 –
但我已經爲當前分配空間,然後在遍歷後,我將溫度分配給當前的權利?那麼這不會在樹中添加新的元素?那麼如何實現呢? –
檢查我的答案。 –