This C Program find 2 nodes with longest distance and display using inorder traversal.
Here is source code of the C Program to find 2 nodes with longest distance and display using inorder traversal. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C Program to Find 2 Nodes with Longest Distance and Display
* using Inorder Traversal
* 40
* /\
* 20 60
* /\ \
* 10 30 80
* \
* 90
*/
#include <stdio.h>
#include <stdlib.h>
struct btnode
{
int value;
struct btnode *left, *right;
};
typedef struct btnode node;
/* function prototypes */
void insert(node *, node *);
void inorder(node *);
int height(node *);
node *temp, *root = NULL;
void main()
{
node *new = NULL ;
int num = 1;
printf("Enter the elements of the tree(enter 0 to exit)\n");
while (1)
{
scanf("%d", &num);
if (num == 0)
break;
new = malloc(sizeof(node));
new->left = new->right = NULL;
new->value = num;
if (root == NULL)
root = new;
else
{
insert(new, root);
}
}
printf("elements in a tree in inorder are\n");
inorder(root);
height(root);
}
/* displaying nodes of a tree using inorder */
void inorder(node *root)
{
if (root != NULL)
{
inorder(root->left);
printf("%d -> ", root->value);
inorder(root->right);
}
}
/* inserting nodes into a tree */
void insert(node * new , node *root)
{
if (new->value>root->value)
{
if (root->right == NULL)
root->right = new;
else
insert(new, root->right);
}
if (new->value<root->value)
{
if (root->left == NULL)
root->left = new;
else
insert(new, root->left);
}
}
/* to find the longest path */
int height(node *temp)
{
temp = root;
if (temp == NULL)
printf("tree is empty\n");
else
{
printf("\nlongest path is\n");
while (temp->left != NULL)
{
if (temp->left == NULL)
temp = temp->right;
else
temp = temp->left;
}
printf("%d ->", temp->value);
temp = root;
while (temp->right != NULL)
{
if (temp->right == NULL)
temp = temp->left;
else
temp = temp->right;
}
printf(" %d", temp->value);
}
}
$ cc tree40.c $ a.out Enter the elements of the tree(enter 0 to exit) 40 20 30 50 60 80 90 0 elements in a tree in inorder are 20 -> 30 -> 40 -> 50 -> 60 -> 80 -> 90 longest path is 20 -> 90
Sanfoundry Global Education & Learning Series – 1000 C Programs.
advertisement
advertisement
Here’s the list of Best Books in C Programming, Data-Structures and Algorithms
If you wish to look at programming examples on all topics, go to C Programming Examples.
Next Steps:
- Get Free Certificate of Merit in Data Structure I
- Participate in Data Structure I Certification Contest
- Become a Top Ranker in Data Structure I
- Take Data Structure I Tests
- Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
- Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Related Posts:
- Practice Computer Science MCQs
- Practice Programming MCQs
- Practice Design & Analysis of Algorithms MCQ
- Buy Programming Books
- Buy Computer Science Books