/*I am trying to form a binary tree from an array of ints. The given code has some flaws.Please help in resolving them.I am using an array"addr[]" to store the addresses of various nodes according to their position in the tree.*/ #include<stdio.h> #include<stdlib.h> typedef struct Node{ int info; struct node *left; struct node *right; }node; void form_tree(int a[],node **root) { int addr[100]; int i; node *ptr; (*root)->info=a[0]; (*root)->left=NULL; (*root)->right=NULL; addr[0]=-1; addr[1]=root; for(i=1;i<10;i++) { node *nw=(node*)malloc(sizeof(node)); nw->info=a[i]; nw->left=NULL; nw->right=NULL; addr[i+1]=&nw; ptr=addr[(i+1)/2]; if((i+1)%2==0) ptr->left=&nw; else ptr->right=&nw; } } int main() { node *ptr; int a[10]={5,10,15,20,25,30,35,40,45,50}; node *root; root=(node*)malloc(sizeof(node)); form_tree(a,&root); ptr=root; while(ptr->left!=NULL) printf("\n%d",ptr->info); getch(); }
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)