New Want to Write for Computaholics ? if Yes Contact us at "contact@computaholics.in"

Parent Node in Binary Tree

Write a program to retrieve all parent node in a binary tree :-

#include<stdio.h>
#include<stdlib.h>

//binary tree program

struct node{
int data;
int parent;
struct node *left;
struct node *right;
};

//struct node *root;

struct node *insert(struct node *node,int x){

if(node==NULL){
struct node *newnode=(struct node *)malloc(sizeof(struct node));
newnode->data=x;
return newnode;
}
else if (node->data>x){
node->left=insert(node->left,x);
}
else if (node->data<x){
node->right=insert(node->right,x);
}

return node;

}

struct node *parent(struct node *node){
if(node==NULL)
return;

node->left=parent(node->left);
if(node->left)
node->left->parent=node->data;
if(node->right)
node->right->parent=node->data;
//printf("%d  ",node->data);
node->right=parent(node->right);

return node;
}

void print(struct node *node){
if(node==NULL)
return;

print(node->left);
printf("node=%d node->parent=%d \n",node->data,node->parent);
print(node->right);
}

int main(){

FILE *fp;
fp=fopen("file.txt","r");
int n,i,x;
struct node *root=NULL;
fscanf(fp,"%d",&n);

for(i=0;i<n;i++){
fscanf(fp,"%d",&x);
root=insert(root,x);

}

parent(root);

print(root);

return 0;
}
Copyright © C Program | Java | OpenGL Programming | Hadoop at Computaholics