#include<stdio.h>
#include<stdlib.h>
struct Btree{
int data;
struct Btree *left;
struct Btree *right;
};
struct Btree *root = NULL;
struct Btree *createTree(int i,int *input,int n){
int leftChild = 2*i+1,rightChild = 2*i+2;
struct Btree *newNode = NULL;
newNode = (struct Btree *)malloc(sizeof(struct Btree));
if(input[i] == -1){
return NULL
}else{
newNode->data = input[i];
newNode->left = NULL;
newNode->right = NULL;
}
if(root == NULL){
root = newNode;
}
if(leftChild > n || input[leftChild] == -1){
newNode->left = NULL;
}else{
newNode->left = createTree(leftChild,input,n);
}
if(rightChild > n || input[rightChild] == -1){
newNode->right = NULL;
}else{
newNode->right = createTree(rightChild,input,n);
}
return newNode;
}
void inorder(struct Btree *root){
if(root){
inorder(root->left);
printf("%d",root->data);
inorder(root->right);
}
}
int main(){
int n,i;
printf("Enter values of N : \t");
scanf("%d",&n);
int input[n];
printf("enter input nodes");
for(i=0;i<n;i++){
scanf("%d",&input[i]);
}
for(i=0;i<n;i++){
printf("%d ",input[i]);
}
printf("\n");
root = createTree(0,input,n);
inorder(root);
return 0;
}
在這個程序中,我試圖構建二叉樹(不是二叉搜索樹)。爲此,我編寫了上面的代碼,但是我遇到了分段錯誤。爲什麼我在這個程序中出現分段錯誤?
我在這做的是從stdin中獲取輸入並將其存儲到輸入數組中,我試圖構建二叉樹。
從評論更新
我輸入的是:
1 2 3 4 -1 -1 5
如果您可以在觀察問題時添加問題所用的輸入,可能會有所幫助。 –
當你建立你的樹時,有三個選項可以設置左邊的孩子,只有這樣才能設置好。並且請使用調試器來查明問題發生的位置。 – Mat
在哪個行動中,您正在獲得seg。故障? – ANjaNA