c implementation:
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node* left;
struct node* right;
};
struct node* newNode(int data)
{
struct node* node=(struct node* )malloc(sizeof(struct node));
node->data=data;
node->left=NULL;
node->right=NULL;
return (node);
}
struct node* insert(struct node* node,int data)
{
if(node==NULL)
return newNode(data);
if(data < node->data)
node->left=insert(node->left,data);
else
node->right=insert(node->right,data);
return(node);
}
void printknode(struct node* node,int k)
{
if(node==NULL)
return;
if(k==0)
printf("%d ",node->data);
else
{
printknode( node->left, k-1 ) ;
printknode( node->right, k-1 ) ;
}
}
void inorder(struct node* node)
{
if(node==NULL)
return;
inorder(node->left);
printf("%d ",node->data);
inorder(node->right);
}
int main()
{
struct node* root=NULL;
root=insert(root,5);
insert(root,6);
insert(root,3);
insert(root,4);
insert(root,7);
printf("\ninorder travesal\n");
inorder(root);
printf("\nkth distance node from root\n");
printknode(root,1);
return 0;
}
#include <stdlib.h>
struct node
{
int data;
struct node* left;
struct node* right;
};
struct node* newNode(int data)
{
struct node* node=(struct node* )malloc(sizeof(struct node));
node->data=data;
node->left=NULL;
node->right=NULL;
return (node);
}
struct node* insert(struct node* node,int data)
{
if(node==NULL)
return newNode(data);
if(data < node->data)
node->left=insert(node->left,data);
else
node->right=insert(node->right,data);
return(node);
}
void printknode(struct node* node,int k)
{
if(node==NULL)
return;
if(k==0)
printf("%d ",node->data);
else
{
printknode( node->left, k-1 ) ;
printknode( node->right, k-1 ) ;
}
}
void inorder(struct node* node)
{
if(node==NULL)
return;
inorder(node->left);
printf("%d ",node->data);
inorder(node->right);
}
int main()
{
struct node* root=NULL;
root=insert(root,5);
insert(root,6);
insert(root,3);
insert(root,4);
insert(root,7);
printf("\ninorder travesal\n");
inorder(root);
printf("\nkth distance node from root\n");
printknode(root,1);
return 0;
}
output:
No comments:
Post a Comment