An array can be converted into a binary tree.
1) Parent : Parent of a node at index lies at (n-1)/2 except the root node.
2) Left Child : Left child of a node at index n lies at (2*n+1).
3) Right Child : Right child of a node at index n lies at (2*n+2).
4) Left Sibling : left Sibling of a node at index n lies at (n-1).
5) Right Sibling : Right sibling of a node at index n lies at (n+1).
C program for converting a list of array into a binary tree.
1) Parent : Parent of a node at index lies at (n-1)/2 except the root node.
2) Left Child : Left child of a node at index n lies at (2*n+1).
3) Right Child : Right child of a node at index n lies at (2*n+2).
4) Left Sibling : left Sibling of a node at index n lies at (n-1).
5) Right Sibling : Right sibling of a node at index n lies at (n+1).
C program for converting a list of array into a binary tree.
//Binary tree Using array /** * *@author VIKASH VIK VIKKU VIKASHVVERMA * */ #include<stdio.h> typedef struct node { struct node*left; struct node*right; char data; }node; node* insert(char c[],int n) { node*tree=NULL; if(c[n]!='\0') { tree=(node*)malloc(sizeof(node)); tree->left=insert(c,2*n+1); tree->data=c[n]; tree->right=insert(c,2*n+2); } return tree; } //traverse the tree in inorder void inorder(node*tree) { if(tree!=NULL) { inorder(tree->left); printf("%c\t",tree->data); inorder(tree->right); } } void main() { node*tree=NULL; char c[]={'A','B','C','D','E','F','\0','G','\0','\0','\0','\0','\0','\0','\0','\0','\0','\0','\0','\0','\0'}; tree=insert(c,0); inorder(tree); }
No comments :
Post a Comment