Print Ancestor of given node value in binary tree.
For Given Binary Search tree find out the ancestor of a given node value .

Node Value O/P
4 8 3 6
13 8 10 14
Recursive function to print ancestor values for given binary search tree.
1 2 3 4 5 6 7 8 9 |
int printances(struct Tnode *Troot1,int nodeval){ if(Troot1==NULL) return 0; if(nodeval==Troot1->val) return 1; if(printances(Troot1->left,nodeval)||printances(Troot1->right,nodeval)) { printf(" %d ",Troot1->val); return 1; } return 0; } |
Complete code with binary search tree implementation and ancestor printing function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
/* Binary Search tree code by condingstreet.com */ #include<stdio.h> #include<stdlib.h> struct Tnode { int val; struct Tnode *left,*right; }; int create_node(int val,struct Tnode **node){ struct Tnode *tmp; tmp=malloc(sizeof(struct Tnode)); if(tmp==NULL) return 0; tmp->val=val; tmp->left=NULL; tmp->right=NULL; (*node)=tmp; return 1; } void insert_node(struct Tnode **Troot,struct Tnode **node){ struct Tnode *parent,*tmp; int val; if((*node)==NULL) return; if((*Troot)==NULL){ (*Troot)=(*node); return; } tmp=(*Troot); val=(*node)->val; while(tmp!=NULL){ parent=tmp; if(val<tmp->val) tmp=tmp->left; else tmp=tmp->right; } if(val<parent->val){ parent->left=(*node); } else parent->right=(*node); return; } int printances(struct Tnode *Troot1,int nodeval){ if(Troot1==NULL) return 0; if(nodeval==Troot1->val) return 1; if(printances(Troot1->left,nodeval)||printances(Troot1->right,nodeval)) printf(" %d ",Troot1->val); } int main(){ struct Tnode *root=NULL,*node; int key,ival; do{ printf("\n[1] Insert value"); printf("\n[2] Print Ancestors "); printf("\n[3] Exit "); printf("\nEnter the input key : "); scanf("%d",&key); switch(key){ case 1: printf("\n Enter the value to be inserted :"); scanf("%d",&ival); if(create_node(ival,&node)) insert_node(&root,&node); else printf("\n Memory is Full !! "); break; case 2: printf("\n Enter the value whose ancestore to be calculated :"); scanf("%d",&ival); printances(root,ival); break; case 3: break; default: printf("\t Enter the Correct key !!!!! "); break; } }while(key!=3); printf("\n Thank you for using codingstreet.com 's datastructure solution "); return 0; } |