SlideShare a Scribd company logo
1 of 9
Download to read offline
C programming. Answer question only in C code In the eighth part, you have to implement a
binary search tree. The tree must satisfy the binary search tree property: the key in each node
must be greater than all keys stored in the left sub-tree, and smaller than all keys in right sub-
tree. You have to dynamically allocate space for each node and free the space for the nodes at the
end of the program. This program takes a file name as an argument from the command line. The
file is either blank or contains successive lines of input. Each line starts with a character, either
'i' or 's' followed by a tab and then an integer. For each line that starts with V, your program
should insert that number in the binary search tree if it is not already there. If it is already
present, you will print "duplicate" and not change the tree. If the line starts with a 's' your
program should search for the value. Output format: For each fine in the input file, your
program should print the status/result of the operation. For an insert operation, the program
should print either "inserted" with a single space followed by a number, the height of the
inserted node in the tree, or "duplicate" if the value is already present in the tree. The height of
the root node is 1. For a search, the program should either print "present", followed by the
height of the node, or "absent" based on the outcome of the search. Your program should print
"error" (and nothing else) if the file does not exist or for input lines with improper structure.
Example Execution: Let's assume we have a file.txt with the following contents: 5 3 4 1 6 s
Executing the program in the following fashion should produce the output shown below:
$./eighth file1.txt inserted 1 inserted 2 inserted 3 inserted 3 inserted 2 present 3.
Solution
Above program only inserts data / nodes to the binary tree. To print the tree, we need to know
how to traverse a Binary Search Tree
C Program to implement Binary Search Tree Traversal
Preorder traversal sequence : F, B, A, D, C, E, G, I, H
(root, left, right)
Inorder traversal sequence : A, B, C, D, E, F, G, H, I
(left, root, right)
Postorder traversal sequence: A, C, E, D, B, H, I, G, F
(left, right, root)
Program :
# include
# include
# include
typedef struct BST {
int data;
struct BST *lchild, *rchild;
} node;
void insert(node *, node *);
void inorder(node *);
void preorder(node *);
void postorder(node *);
node *search(node *, int, node **);
void main() {
int choice;
char ans = 'N';
int key;
node *new_node, *root, *tmp, *parent;
node *get_node();
root = NULL;
clrscr();
printf(" Program For Binary Search Tree ");
do {
printf(" 1.Create");
printf(" 2.Search");
printf(" 3.Recursive Traversals");
printf(" 4.Exit");
printf(" Enter your choice :");
scanf("%d", &choice);
switch (choice) {
case 1:
do {
new_node = get_node();
printf(" Enter The Element ");
scanf("%d", &new_node->data);
if (root == NULL) /* Tree is not Created */
root = new_node;
else
insert(root, new_node);
printf(" Want To enter More Elements?(y/n)");
ans = getch();
} while (ans == 'y');
break;
case 2:
printf(" Enter Element to be searched :");
scanf("%d", &key);
tmp = search(root, key, &parent);
printf(" Parent of node %d is %d", tmp->data, parent->data);
break;
case 3:
if (root == NULL)
printf("Tree Is Not Created");
else {
printf(" The Inorder display : ");
inorder(root);
printf(" The Preorder display : ");
preorder(root);
printf(" The Postorder display : ");
postorder(root);
}
break;
}
} while (choice != 4);
}
/*
Get new Node
*/
node *get_node() {
node *temp;
temp = (node *) malloc(sizeof(node));
temp->lchild = NULL;
temp->rchild = NULL;
return temp;
}
/*
This function is for creating a binary search tree
*/
void insert(node *root, node *new_node) {
if (new_node->data < root->data) {
if (root->lchild == NULL)
root->lchild = new_node;
else
insert(root->lchild, new_node);
}
if (new_node->data > root->data) {
if (root->rchild == NULL)
root->rchild = new_node;
else
insert(root->rchild, new_node);
}
}
/*
This function is for searching the node from
binary Search Tree
*/
node *search(node *root, int key, node **parent) {
node *temp;
temp = root;
while (temp != NULL) {
if (temp->data == key) {
printf(" The %d Element is Present", temp->data);
return temp;
}
*parent = temp;
if (temp->data > key)
temp = temp->lchild;
else
temp = temp->rchild;
}
return NULL;
}
/*
This function displays the tree in inorder fashion
*/
void inorder(node *temp) {
if (temp != NULL) {
inorder(temp->lchild);
printf("%d", temp->data);
inorder(temp->rchild);
}
}
/*
This function displays the tree in preorder fashion
*/
void preorder(node *temp) {
if (temp != NULL) {
printf("%d", temp->data);
preorder(temp->lchild);
preorder(temp->rchild);
}
}
/*
This function displays the tree in postorder fashion
*/
void postorder(node *temp) {
if (temp != NULL) {
postorder(temp->lchild);
postorder(temp->rchild);
printf("%d", temp->data);
}
}
Explanation :
if(root == NULL)
# include
# include
# include
typedef struct BST {
int data;
struct BST *lchild, *rchild;
} node;
void insert(node *, node *);
void inorder(node *);
void preorder(node *);
void postorder(node *);
node *search(node *, int, node **);
void main() {
int choice;
char ans = 'N';
int key;
node *new_node, *root, *tmp, *parent;
node *get_node();
root = NULL;
clrscr();
printf(" Program For Binary Search Tree ");
do {
printf(" 1.Create");
printf(" 2.Search");
printf(" 3.Recursive Traversals");
printf(" 4.Exit");
printf(" Enter your choice :");
scanf("%d", &choice);
switch (choice) {
case 1:
do {
new_node = get_node();
printf(" Enter The Element ");
scanf("%d", &new_node->data);
if (root == NULL) /* Tree is not Created */
root = new_node;
else
insert(root, new_node);
printf(" Want To enter More Elements?(y/n)");
ans = getch();
} while (ans == 'y');
break;
case 2:
printf(" Enter Element to be searched :");
scanf("%d", &key);
tmp = search(root, key, &parent);
printf(" Parent of node %d is %d", tmp->data, parent->data);
break;
case 3:
if (root == NULL)
printf("Tree Is Not Created");
else {
printf(" The Inorder display : ");
inorder(root);
printf(" The Preorder display : ");
preorder(root);
printf(" The Postorder display : ");
postorder(root);
}
break;
}
} while (choice != 4);
}
/*
Get new Node
*/
node *get_node() {
node *temp;
temp = (node *) malloc(sizeof(node));
temp->lchild = NULL;
temp->rchild = NULL;
return temp;
}
/*
This function is for creating a binary search tree
*/
void insert(node *root, node *new_node) {
if (new_node->data < root->data) {
if (root->lchild == NULL)
root->lchild = new_node;
else
insert(root->lchild, new_node);
}
if (new_node->data > root->data) {
if (root->rchild == NULL)
root->rchild = new_node;
else
insert(root->rchild, new_node);
}
}
/*
This function is for searching the node from
binary Search Tree
*/
node *search(node *root, int key, node **parent) {
node *temp;
temp = root;
while (temp != NULL) {
if (temp->data == key) {
printf(" The %d Element is Present", temp->data);
return temp;
}
*parent = temp;
if (temp->data > key)
temp = temp->lchild;
else
temp = temp->rchild;
}
return NULL;
}
/*
This function displays the tree in inorder fashion
*/
void inorder(node *temp) {
if (temp != NULL) {
inorder(temp->lchild);
printf("%d", temp->data);
inorder(temp->rchild);
}
}
/*
This function displays the tree in preorder fashion
*/
void preorder(node *temp) {
if (temp != NULL) {
printf("%d", temp->data);
preorder(temp->lchild);
preorder(temp->rchild);
}
}
/*
This function displays the tree in postorder fashion
*/
void postorder(node *temp) {
if (temp != NULL) {
postorder(temp->lchild);
postorder(temp->rchild);
printf("%d", temp->data);
}
}

More Related Content

Similar to C programming. Answer question only in C code In the eighth part, yo.pdf

You must implement the following functions- Name the functions exactly.docx
You must implement the following functions- Name the functions exactly.docxYou must implement the following functions- Name the functions exactly.docx
You must implement the following functions- Name the functions exactly.docx
Sebastian6SWSlaterb
 
Please answer the 4 questions using C- The expected output is shown be.docx
Please answer the 4 questions using C- The expected output is shown be.docxPlease answer the 4 questions using C- The expected output is shown be.docx
Please answer the 4 questions using C- The expected output is shown be.docx
cgraciela1
 
Create an implementation of a binary tree using the recursive appr.pdf
Create an implementation of a binary tree using the recursive appr.pdfCreate an implementation of a binary tree using the recursive appr.pdf
Create an implementation of a binary tree using the recursive appr.pdf
federaleyecare
 
IN C LANGUAGE- I've been trying to finish this program for the last fe.docx
IN C LANGUAGE- I've been trying to finish this program for the last fe.docxIN C LANGUAGE- I've been trying to finish this program for the last fe.docx
IN C LANGUAGE- I've been trying to finish this program for the last fe.docx
GordonpACKellyb
 
So I am writing a CS code for a project and I keep getting cannot .pdf
So I am writing a CS code for a project and I keep getting cannot .pdfSo I am writing a CS code for a project and I keep getting cannot .pdf
So I am writing a CS code for a project and I keep getting cannot .pdf
ezonesolutions
 
Input output functions
Input output functionsInput output functions
Input output functions
hyderali123
 
Recursive descent parsing
Recursive descent parsingRecursive descent parsing
Recursive descent parsing
Boy Baukema
 
In C pls -- Write your name here -- Write the compiler used- Visual st.docx
In C pls -- Write your name here -- Write the compiler used- Visual st.docxIn C pls -- Write your name here -- Write the compiler used- Visual st.docx
In C pls -- Write your name here -- Write the compiler used- Visual st.docx
Blake0FxCampbelld
 
^^^Q2. Discuss about Header Node    And also write a program fo.pdf
^^^Q2. Discuss about Header Node    And also write a program fo.pdf^^^Q2. Discuss about Header Node    And also write a program fo.pdf
^^^Q2. Discuss about Header Node    And also write a program fo.pdf
arjunhassan8
 

Similar to C programming. Answer question only in C code In the eighth part, yo.pdf (20)

Final ds record
Final ds recordFinal ds record
Final ds record
 
01 list using array
01 list using array01 list using array
01 list using array
 
Data Structure in C (Lab Programs)
Data Structure in C (Lab Programs)Data Structure in C (Lab Programs)
Data Structure in C (Lab Programs)
 
VTU DSA Lab Manual
VTU DSA Lab ManualVTU DSA Lab Manual
VTU DSA Lab Manual
 
week-14x
week-14xweek-14x
week-14x
 
You must implement the following functions- Name the functions exactly.docx
You must implement the following functions- Name the functions exactly.docxYou must implement the following functions- Name the functions exactly.docx
You must implement the following functions- Name the functions exactly.docx
 
DS UNIT3_LINKED LISTS.docx
DS UNIT3_LINKED LISTS.docxDS UNIT3_LINKED LISTS.docx
DS UNIT3_LINKED LISTS.docx
 
Please answer the 4 questions using C- The expected output is shown be.docx
Please answer the 4 questions using C- The expected output is shown be.docxPlease answer the 4 questions using C- The expected output is shown be.docx
Please answer the 4 questions using C- The expected output is shown be.docx
 
Create an implementation of a binary tree using the recursive appr.pdf
Create an implementation of a binary tree using the recursive appr.pdfCreate an implementation of a binary tree using the recursive appr.pdf
Create an implementation of a binary tree using the recursive appr.pdf
 
IN C LANGUAGE- I've been trying to finish this program for the last fe.docx
IN C LANGUAGE- I've been trying to finish this program for the last fe.docxIN C LANGUAGE- I've been trying to finish this program for the last fe.docx
IN C LANGUAGE- I've been trying to finish this program for the last fe.docx
 
So I am writing a CS code for a project and I keep getting cannot .pdf
So I am writing a CS code for a project and I keep getting cannot .pdfSo I am writing a CS code for a project and I keep getting cannot .pdf
So I am writing a CS code for a project and I keep getting cannot .pdf
 
linkedlist.pptx
linkedlist.pptxlinkedlist.pptx
linkedlist.pptx
 
Input output functions
Input output functionsInput output functions
Input output functions
 
Recursive descent parsing
Recursive descent parsingRecursive descent parsing
Recursive descent parsing
 
Discuss about Header Node And also write a program for unordered si.pdf
Discuss about Header Node  And also write a program for unordered si.pdfDiscuss about Header Node  And also write a program for unordered si.pdf
Discuss about Header Node And also write a program for unordered si.pdf
 
Easy R
Easy REasy R
Easy R
 
In C pls -- Write your name here -- Write the compiler used- Visual st.docx
In C pls -- Write your name here -- Write the compiler used- Visual st.docxIn C pls -- Write your name here -- Write the compiler used- Visual st.docx
In C pls -- Write your name here -- Write the compiler used- Visual st.docx
 
C
CC
C
 
Programming in C
Programming in CProgramming in C
Programming in C
 
^^^Q2. Discuss about Header Node    And also write a program fo.pdf
^^^Q2. Discuss about Header Node    And also write a program fo.pdf^^^Q2. Discuss about Header Node    And also write a program fo.pdf
^^^Q2. Discuss about Header Node    And also write a program fo.pdf
 

More from mohammedfootwear

Getting some errors when trying to run this program, can anyone help.pdf
Getting some errors when trying to run this program, can anyone help.pdfGetting some errors when trying to run this program, can anyone help.pdf
Getting some errors when trying to run this program, can anyone help.pdf
mohammedfootwear
 
Describe one safeguard that should be in place to protect the confid.pdf
Describe one safeguard that should be in place to protect the confid.pdfDescribe one safeguard that should be in place to protect the confid.pdf
Describe one safeguard that should be in place to protect the confid.pdf
mohammedfootwear
 
Create a storyboard prototype of a mobile app.When creating a stor.pdf
Create a storyboard prototype of a mobile app.When creating a stor.pdfCreate a storyboard prototype of a mobile app.When creating a stor.pdf
Create a storyboard prototype of a mobile app.When creating a stor.pdf
mohammedfootwear
 
Adding methods to the ListBag classIn the file ListBag.py, add the.pdf
Adding methods to the ListBag classIn the file ListBag.py, add the.pdfAdding methods to the ListBag classIn the file ListBag.py, add the.pdf
Adding methods to the ListBag classIn the file ListBag.py, add the.pdf
mohammedfootwear
 
5. value 10.00 polnts On May 1, Soriano Co. reported the following ac.pdf
5. value 10.00 polnts On May 1, Soriano Co. reported the following ac.pdf5. value 10.00 polnts On May 1, Soriano Co. reported the following ac.pdf
5. value 10.00 polnts On May 1, Soriano Co. reported the following ac.pdf
mohammedfootwear
 
You will choose a country, other than the USA or Turkey, that you wo.pdf
You will choose a country, other than the USA or Turkey, that you wo.pdfYou will choose a country, other than the USA or Turkey, that you wo.pdf
You will choose a country, other than the USA or Turkey, that you wo.pdf
mohammedfootwear
 
What is the correct answer Chrome File Edit View History Bookmarks.pdf
What is the correct answer Chrome File Edit View History Bookmarks.pdfWhat is the correct answer Chrome File Edit View History Bookmarks.pdf
What is the correct answer Chrome File Edit View History Bookmarks.pdf
mohammedfootwear
 
Using SQL Developer ONLY!Your assignment is to create an auditing .pdf
Using SQL Developer ONLY!Your assignment is to create an auditing .pdfUsing SQL Developer ONLY!Your assignment is to create an auditing .pdf
Using SQL Developer ONLY!Your assignment is to create an auditing .pdf
mohammedfootwear
 
This for English class.I need help for writing 4 to 5 paragraphs a.pdf
This for English class.I need help for writing 4 to 5 paragraphs a.pdfThis for English class.I need help for writing 4 to 5 paragraphs a.pdf
This for English class.I need help for writing 4 to 5 paragraphs a.pdf
mohammedfootwear
 

More from mohammedfootwear (20)

Getting some errors when trying to run this program, can anyone help.pdf
Getting some errors when trying to run this program, can anyone help.pdfGetting some errors when trying to run this program, can anyone help.pdf
Getting some errors when trying to run this program, can anyone help.pdf
 
Discuss what is meant by Project Scope ManagementSolutionA pr.pdf
Discuss what is meant by Project Scope ManagementSolutionA pr.pdfDiscuss what is meant by Project Scope ManagementSolutionA pr.pdf
Discuss what is meant by Project Scope ManagementSolutionA pr.pdf
 
Determine if statement is true or false. If johnny likes suzy the ri.pdf
Determine if statement is true or false. If johnny likes suzy the ri.pdfDetermine if statement is true or false. If johnny likes suzy the ri.pdf
Determine if statement is true or false. If johnny likes suzy the ri.pdf
 
Describe one safeguard that should be in place to protect the confid.pdf
Describe one safeguard that should be in place to protect the confid.pdfDescribe one safeguard that should be in place to protect the confid.pdf
Describe one safeguard that should be in place to protect the confid.pdf
 
Create a storyboard prototype of a mobile app.When creating a stor.pdf
Create a storyboard prototype of a mobile app.When creating a stor.pdfCreate a storyboard prototype of a mobile app.When creating a stor.pdf
Create a storyboard prototype of a mobile app.When creating a stor.pdf
 
Are you familiar with the term parochialism What could be happen.pdf
Are you familiar with the term parochialism What could be happen.pdfAre you familiar with the term parochialism What could be happen.pdf
Are you familiar with the term parochialism What could be happen.pdf
 
Answer the question, What market structure is the airline industry.pdf
Answer the question, What market structure is the airline industry.pdfAnswer the question, What market structure is the airline industry.pdf
Answer the question, What market structure is the airline industry.pdf
 
Adding methods to the ListBag classIn the file ListBag.py, add the.pdf
Adding methods to the ListBag classIn the file ListBag.py, add the.pdfAdding methods to the ListBag classIn the file ListBag.py, add the.pdf
Adding methods to the ListBag classIn the file ListBag.py, add the.pdf
 
5. value 10.00 polnts On May 1, Soriano Co. reported the following ac.pdf
5. value 10.00 polnts On May 1, Soriano Co. reported the following ac.pdf5. value 10.00 polnts On May 1, Soriano Co. reported the following ac.pdf
5. value 10.00 polnts On May 1, Soriano Co. reported the following ac.pdf
 
Biology Lab questions1. Why can a very small amount of bacteria b.pdf
Biology Lab questions1. Why can a very small amount of bacteria b.pdfBiology Lab questions1. Why can a very small amount of bacteria b.pdf
Biology Lab questions1. Why can a very small amount of bacteria b.pdf
 
You will choose a country, other than the USA or Turkey, that you wo.pdf
You will choose a country, other than the USA or Turkey, that you wo.pdfYou will choose a country, other than the USA or Turkey, that you wo.pdf
You will choose a country, other than the USA or Turkey, that you wo.pdf
 
Why does the RNA polymerase complex in eukaryotes contain a histone .pdf
Why does the RNA polymerase complex in eukaryotes contain a histone .pdfWhy does the RNA polymerase complex in eukaryotes contain a histone .pdf
Why does the RNA polymerase complex in eukaryotes contain a histone .pdf
 
what Linux command allows you to scan the disk for partition changes.pdf
what Linux command allows you to scan the disk for partition changes.pdfwhat Linux command allows you to scan the disk for partition changes.pdf
what Linux command allows you to scan the disk for partition changes.pdf
 
What is the correct answer Chrome File Edit View History Bookmarks.pdf
What is the correct answer Chrome File Edit View History Bookmarks.pdfWhat is the correct answer Chrome File Edit View History Bookmarks.pdf
What is the correct answer Chrome File Edit View History Bookmarks.pdf
 
What is fault tolerance, and what network aspects must be monitored .pdf
What is fault tolerance, and what network aspects must be monitored .pdfWhat is fault tolerance, and what network aspects must be monitored .pdf
What is fault tolerance, and what network aspects must be monitored .pdf
 
Using SQL Developer ONLY!Your assignment is to create an auditing .pdf
Using SQL Developer ONLY!Your assignment is to create an auditing .pdfUsing SQL Developer ONLY!Your assignment is to create an auditing .pdf
Using SQL Developer ONLY!Your assignment is to create an auditing .pdf
 
Use the definition of big- Theta to prove that 5x^4 + 2x^3 - 1 is The.pdf
Use the definition of big- Theta to prove that 5x^4 + 2x^3 - 1 is The.pdfUse the definition of big- Theta to prove that 5x^4 + 2x^3 - 1 is The.pdf
Use the definition of big- Theta to prove that 5x^4 + 2x^3 - 1 is The.pdf
 
To what degree, if any, has America’s ascendancy on the world stage .pdf
To what degree, if any, has America’s ascendancy on the world stage .pdfTo what degree, if any, has America’s ascendancy on the world stage .pdf
To what degree, if any, has America’s ascendancy on the world stage .pdf
 
This for English class.I need help for writing 4 to 5 paragraphs a.pdf
This for English class.I need help for writing 4 to 5 paragraphs a.pdfThis for English class.I need help for writing 4 to 5 paragraphs a.pdf
This for English class.I need help for writing 4 to 5 paragraphs a.pdf
 
The debt ratio is the relationship between O A. total assets and cur.pdf
The debt ratio is the relationship between O A. total assets and cur.pdfThe debt ratio is the relationship between O A. total assets and cur.pdf
The debt ratio is the relationship between O A. total assets and cur.pdf
 

Recently uploaded

Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
KarakKing
 

Recently uploaded (20)

COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
Salient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functionsSalient Features of India constitution especially power and functions
Salient Features of India constitution especially power and functions
 
Plant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxPlant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptx
 
Basic Intentional Injuries Health Education
Basic Intentional Injuries Health EducationBasic Intentional Injuries Health Education
Basic Intentional Injuries Health Education
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17
 

C programming. Answer question only in C code In the eighth part, yo.pdf

  • 1. C programming. Answer question only in C code In the eighth part, you have to implement a binary search tree. The tree must satisfy the binary search tree property: the key in each node must be greater than all keys stored in the left sub-tree, and smaller than all keys in right sub- tree. You have to dynamically allocate space for each node and free the space for the nodes at the end of the program. This program takes a file name as an argument from the command line. The file is either blank or contains successive lines of input. Each line starts with a character, either 'i' or 's' followed by a tab and then an integer. For each line that starts with V, your program should insert that number in the binary search tree if it is not already there. If it is already present, you will print "duplicate" and not change the tree. If the line starts with a 's' your program should search for the value. Output format: For each fine in the input file, your program should print the status/result of the operation. For an insert operation, the program should print either "inserted" with a single space followed by a number, the height of the inserted node in the tree, or "duplicate" if the value is already present in the tree. The height of the root node is 1. For a search, the program should either print "present", followed by the height of the node, or "absent" based on the outcome of the search. Your program should print "error" (and nothing else) if the file does not exist or for input lines with improper structure. Example Execution: Let's assume we have a file.txt with the following contents: 5 3 4 1 6 s Executing the program in the following fashion should produce the output shown below: $./eighth file1.txt inserted 1 inserted 2 inserted 3 inserted 3 inserted 2 present 3. Solution Above program only inserts data / nodes to the binary tree. To print the tree, we need to know how to traverse a Binary Search Tree C Program to implement Binary Search Tree Traversal Preorder traversal sequence : F, B, A, D, C, E, G, I, H (root, left, right) Inorder traversal sequence : A, B, C, D, E, F, G, H, I (left, root, right) Postorder traversal sequence: A, C, E, D, B, H, I, G, F (left, right, root) Program : # include # include # include
  • 2. typedef struct BST { int data; struct BST *lchild, *rchild; } node; void insert(node *, node *); void inorder(node *); void preorder(node *); void postorder(node *); node *search(node *, int, node **); void main() { int choice; char ans = 'N'; int key; node *new_node, *root, *tmp, *parent; node *get_node(); root = NULL; clrscr(); printf(" Program For Binary Search Tree "); do { printf(" 1.Create"); printf(" 2.Search"); printf(" 3.Recursive Traversals"); printf(" 4.Exit"); printf(" Enter your choice :"); scanf("%d", &choice); switch (choice) { case 1: do { new_node = get_node(); printf(" Enter The Element "); scanf("%d", &new_node->data); if (root == NULL) /* Tree is not Created */ root = new_node; else insert(root, new_node); printf(" Want To enter More Elements?(y/n)");
  • 3. ans = getch(); } while (ans == 'y'); break; case 2: printf(" Enter Element to be searched :"); scanf("%d", &key); tmp = search(root, key, &parent); printf(" Parent of node %d is %d", tmp->data, parent->data); break; case 3: if (root == NULL) printf("Tree Is Not Created"); else { printf(" The Inorder display : "); inorder(root); printf(" The Preorder display : "); preorder(root); printf(" The Postorder display : "); postorder(root); } break; } } while (choice != 4); } /* Get new Node */ node *get_node() { node *temp; temp = (node *) malloc(sizeof(node)); temp->lchild = NULL; temp->rchild = NULL; return temp; } /* This function is for creating a binary search tree
  • 4. */ void insert(node *root, node *new_node) { if (new_node->data < root->data) { if (root->lchild == NULL) root->lchild = new_node; else insert(root->lchild, new_node); } if (new_node->data > root->data) { if (root->rchild == NULL) root->rchild = new_node; else insert(root->rchild, new_node); } } /* This function is for searching the node from binary Search Tree */ node *search(node *root, int key, node **parent) { node *temp; temp = root; while (temp != NULL) { if (temp->data == key) { printf(" The %d Element is Present", temp->data); return temp; } *parent = temp; if (temp->data > key) temp = temp->lchild; else temp = temp->rchild; } return NULL; } /*
  • 5. This function displays the tree in inorder fashion */ void inorder(node *temp) { if (temp != NULL) { inorder(temp->lchild); printf("%d", temp->data); inorder(temp->rchild); } } /* This function displays the tree in preorder fashion */ void preorder(node *temp) { if (temp != NULL) { printf("%d", temp->data); preorder(temp->lchild); preorder(temp->rchild); } } /* This function displays the tree in postorder fashion */ void postorder(node *temp) { if (temp != NULL) { postorder(temp->lchild); postorder(temp->rchild); printf("%d", temp->data); } } Explanation : if(root == NULL) # include # include # include typedef struct BST {
  • 6. int data; struct BST *lchild, *rchild; } node; void insert(node *, node *); void inorder(node *); void preorder(node *); void postorder(node *); node *search(node *, int, node **); void main() { int choice; char ans = 'N'; int key; node *new_node, *root, *tmp, *parent; node *get_node(); root = NULL; clrscr(); printf(" Program For Binary Search Tree "); do { printf(" 1.Create"); printf(" 2.Search"); printf(" 3.Recursive Traversals"); printf(" 4.Exit"); printf(" Enter your choice :"); scanf("%d", &choice); switch (choice) { case 1: do { new_node = get_node(); printf(" Enter The Element "); scanf("%d", &new_node->data); if (root == NULL) /* Tree is not Created */ root = new_node; else insert(root, new_node); printf(" Want To enter More Elements?(y/n)"); ans = getch();
  • 7. } while (ans == 'y'); break; case 2: printf(" Enter Element to be searched :"); scanf("%d", &key); tmp = search(root, key, &parent); printf(" Parent of node %d is %d", tmp->data, parent->data); break; case 3: if (root == NULL) printf("Tree Is Not Created"); else { printf(" The Inorder display : "); inorder(root); printf(" The Preorder display : "); preorder(root); printf(" The Postorder display : "); postorder(root); } break; } } while (choice != 4); } /* Get new Node */ node *get_node() { node *temp; temp = (node *) malloc(sizeof(node)); temp->lchild = NULL; temp->rchild = NULL; return temp; } /* This function is for creating a binary search tree */
  • 8. void insert(node *root, node *new_node) { if (new_node->data < root->data) { if (root->lchild == NULL) root->lchild = new_node; else insert(root->lchild, new_node); } if (new_node->data > root->data) { if (root->rchild == NULL) root->rchild = new_node; else insert(root->rchild, new_node); } } /* This function is for searching the node from binary Search Tree */ node *search(node *root, int key, node **parent) { node *temp; temp = root; while (temp != NULL) { if (temp->data == key) { printf(" The %d Element is Present", temp->data); return temp; } *parent = temp; if (temp->data > key) temp = temp->lchild; else temp = temp->rchild; } return NULL; } /* This function displays the tree in inorder fashion
  • 9. */ void inorder(node *temp) { if (temp != NULL) { inorder(temp->lchild); printf("%d", temp->data); inorder(temp->rchild); } } /* This function displays the tree in preorder fashion */ void preorder(node *temp) { if (temp != NULL) { printf("%d", temp->data); preorder(temp->lchild); preorder(temp->rchild); } } /* This function displays the tree in postorder fashion */ void postorder(node *temp) { if (temp != NULL) { postorder(temp->lchild); postorder(temp->rchild); printf("%d", temp->data); } }