SlideShare a Scribd company logo
1 of 13
Download to read offline
in this assignment you are asked to write a simple driver program and set of functions (maybein
a library) that can be performed on a binary search tree.
Your program should allow user to insert/delete integer values into the binary search tree along
with several other operations on the binary search tree. You can use the code given in slides. But
this time your key will be int! Specifically, your program will ask user to enter a command and
related parameters (if any) in a loop, and then perform the given commands. Here is the list of
commands that your program must implement:
* insert
*find'
*delete
*list inorder
*list preorder
*list postorder
*list levelorder
* max
* min
* height
*count
* sum
*quit
As always, make sure you release (free) the dynamically allocated memories if you allocate any
memory in your programs. So, before submitting your program, run it with valgrind to see if
there is any memory leakage
//my proggram in C
struct tree_node {
int data;
struct tree_node *left, *right;
}
typedef struct nodeT {
int key;
struct nodeT *left, *right;
} nodeT, *treeT;
int main(){
while (TRUE) {
printf("> ");
line = GetLine();
ch = toupper(line[0]);
switch (ch) {
case 'I': insert(); break;
case 'F': find(); break;
case 'D': delete(); break;
case 'LI': listInorder; break;
case 'LPR': listPreorder(); break;
case 'LPO': listPostorder(); break;
case 'MAX': max(); break;
case 'min': min(); break;
case 'H': height(); break;
case 'C': count(); break;
case 'S': sum(); break;
case 'Q': exit(0);
default:printf("Illegal command "); break;
}
}
}
nodeT *FindNode(nodeT *t, int key){
while(t !=NULL) {
if (key == t->key) return t;
if (key < t->key) {
t = t->left;
} else {
t = t->right;
}
return NULL;
}
void delete(nodeT **p){
nodeT
*target;
target=*p;
if (target->left==NULL && target->right==NULL) {
*p=NULL;
} else if (target->left == NULL) {
*p=target->right;
} else
if (target->right == NULL) {
*p=target->left;
} else {
/* target has two children, see next slide */
}
free(target);
}
void listInorder(nodeT *T){
if (t != NULL) {
DisplayTree(t->left);
printf(“%d “, t->key);
DisplayTree(t->right);
}
}
void listPreorder(nodeT *t) {
if (t != NULL) {
printf(“%d “, t->key);
DisplayTree(t->left);
DisplayTree(t->right);
}
}
void listPostOrder(nodeT *t){
if (t != NULL) {
DisplayTree(t->left);
DisplayTree(t->right);
printf(“%d “, t->key);
}
}
void intsert(nodeT **tptr, int key){
nodeT*t, *tmp;
t=*tptr;
if (t == NULL) {
tmp=New(nodeT*);
tmp->key = key;
tmp->left=tmp->right=NULL;
*tptr=tmp;
return;
}
if (key < t->key) {
InsertNode
(&t->left, key);
} else {
InsertNode(&t->right, key);
}
}
int height(nodeT *t){
if (t == NULL)
return 0;
else
return (1 + maximumof(
height(t->left),
height(t->right)) );
}
int sum(struct tree_node *p){
if (p == NULL)
return 0;
else
return (p->data +
sum(p->left) +
sum(p->right) );
}
Solution
1. /*
2. * Java Program to Implement Binary Search Tree
3. */
4.
5. import java.util.Scanner;
6.
7. /* Class BSTNode */
8. class BSTNode
9. {
10. BSTNode left, right;
11. int data;
12.
13. /* Constructor */
14. public BSTNode()
15. {
16. left = null;
17. right = null;
18. data = 0;
19. }
20. /* Constructor */
21. public BSTNode(int n)
22. {
23. left = null;
24. right = null;
25. data = n;
26. }
27. /* Function to set left node */
28. public void setLeft(BSTNode n)
29. {
30. left = n;
31. }
32. /* Function to set right node */
33. public void setRight(BSTNode n)
34. {
35. right = n;
36. }
37. /* Function to get left node */
38. public BSTNode getLeft()
39. {
40. return left;
41. }
42. /* Function to get right node */
43. public BSTNode getRight()
44. {
45. return right;
46. }
47. /* Function to set data to node */
48. public void setData(int d)
49. {
50. data = d;
51. }
52. /* Function to get data from node */
53. public int getData()
54. {
55. return data;
56. }
57. }
58.
59. /* Class BST */
60. class BST
61. {
62. private BSTNode root;
63.
64. /* Constructor */
65. public BST()
66. {
67. root = null;
68. }
69. /* Function to check if tree is empty */
70. public boolean isEmpty()
71. {
72. return root == null;
73. }
74. /* Functions to insert data */
75. public void insert(int data)
76. {
77. root = insert(root, data);
78. }
79. /* Function to insert data recursively */
80. private BSTNode insert(BSTNode node, int data)
81. {
82. if (node == null)
83. node = new BSTNode(data);
84. else
85. {
86. if (data <= node.getData())
87. node.left = insert(node.left, data);
88. else
89. node.right = insert(node.right, data);
90. }
91. return node;
92. }
93. /* Functions to delete data */
94. public void delete(int k)
95. {
96. if (isEmpty())
97. System.out.println("Tree Empty");
98. else if (search(k) == false)
99. System.out.println("Sorry "+ k +" is not present");
100. else
101. {
102. root = delete(root, k);
103. System.out.println(k+ " deleted from the tree");
104. }
105. }
106. private BSTNode delete(BSTNode root, int k)
107. {
108. BSTNode p, p2, n;
109. if (root.getData() == k)
110. {
111. BSTNode lt, rt;
112. lt = root.getLeft();
113. rt = root.getRight();
114. if (lt == null && rt == null)
115. return null;
116. else if (lt == null)
117. {
118. p = rt;
119. return p;
120. }
121. else if (rt == null)
122. {
123. p = lt;
124. return p;
125. }
126. else
127. {
128. p2 = rt;
129. p = rt;
130. while (p.getLeft() != null)
131. p = p.getLeft();
132. p.setLeft(lt);
133. return p2;
134. }
135. }
136. if (k < root.getData())
137. {
138. n = delete(root.getLeft(), k);
139. root.setLeft(n);
140. }
141. else
142. {
143. n = delete(root.getRight(), k);
144. root.setRight(n);
145. }
146. return root;
147. }
148. /* Functions to count number of nodes */
149. public int countNodes()
150. {
151. return countNodes(root);
152. }
153. /* Function to count number of nodes recursively */
154. private int countNodes(BSTNode r)
155. {
156. if (r == null)
157. return 0;
158. else
159. {
160. int l = 1;
161. l += countNodes(r.getLeft());
162. l += countNodes(r.getRight());
163. return l;
164. }
165. }
166. /* Functions to search for an element */
167. public boolean search(int val)
168. {
169. return search(root, val);
170. }
171. /* Function to search for an element recursively */
172. private boolean search(BSTNode r, int val)
173. {
174. boolean found = false;
175. while ((r != null) && !found)
176. {
177. int rval = r.getData();
178. if (val < rval)
179. r = r.getLeft();
180. else if (val > rval)
181. r = r.getRight();
182. else
183. {
184. found = true;
185. break;
186. }
187. found = search(r, val);
188. }
189. return found;
190. }
191. /* Function for inorder traversal */
192. public void inorder()
193. {
194. inorder(root);
195. }
196. private void inorder(BSTNode r)
197. {
198. if (r != null)
199. {
200. inorder(r.getLeft());
201. System.out.print(r.getData() +" ");
202. inorder(r.getRight());
203. }
204. }
205. /* Function for preorder traversal */
206. public void preorder()
207. {
208. preorder(root);
209. }
210. private void preorder(BSTNode r)
211. {
212. if (r != null)
213. {
214. System.out.print(r.getData() +" ");
215. preorder(r.getLeft());
216. preorder(r.getRight());
217. }
218. }
219. /* Function for postorder traversal */
220. public void postorder()
221. {
222. postorder(root);
223. }
224. private void postorder(BSTNode r)
225. {
226. if (r != null)
227. {
228. postorder(r.getLeft());
229. postorder(r.getRight());
230. System.out.print(r.getData() +" ");
231. }
232. }
233. }
234.
235. /* Class BinarySearchTree */
236. public class BinarySearchTree
237. {
238. public static void main(String[] args)
239. {
240. Scanner scan = new Scanner(System.in);
241. /* Creating object of BST */
242. BST bst = new BST();
243. System.out.println("Binary Search Tree Test ");
244. char ch;
245. /* Perform tree operations */
246. do
247. {
248. System.out.println(" Binary Search Tree Operations ");
249. System.out.println("1. insert ");
250. System.out.println("2. delete");
251. System.out.println("3. search");
252. System.out.println("4. count nodes");
253. System.out.println("5. check empty");
254.
255. int choice = scan.nextInt();
256. switch (choice)
257. {
258. case 1 :
259. System.out.println("Enter integer element to insert");
260. bst.insert( scan.nextInt() );
261. break;
262. case 2 :
263. System.out.println("Enter integer element to delete");
264. bst.delete( scan.nextInt() );
265. break;
266. case 3 :
267. System.out.println("Enter integer element to search");
268. System.out.println("Search result : "+ bst.search( scan.nextInt() ));
269. break;
270. case 4 :
271. System.out.println("Nodes = "+ bst.countNodes());
272. break;
273. case 5 :
274. System.out.println("Empty status = "+ bst.isEmpty());
275. break;
276. default :
277. System.out.println("Wrong Entry  ");
278. break;
279. }
280. /* Display tree */
281. System.out.print(" Post order : ");
282. bst.postorder();
283. System.out.print(" Pre order : ");
284. bst.preorder();
285. System.out.print(" In order : ");
286. bst.inorder();
287.
288. System.out.println(" Do you want to continue (Type y or n)  ");
289. ch = scan.next().charAt(0);
290. } while (ch == 'Y'|| ch == 'y');
291. }
292. }

More Related Content

Similar to in this assignment you are asked to write a simple driver program an.pdf

VTU DSA Lab Manual
VTU DSA Lab ManualVTU DSA Lab Manual
VTU DSA Lab ManualAkhilaaReddy
 
This is a c++ binary search program I worked so far but still cant g.pdf
This is a c++ binary search program I worked so far but still cant g.pdfThis is a c++ binary search program I worked so far but still cant g.pdf
This is a c++ binary search program I worked so far but still cant g.pdfkostikjaylonshaewe47
 
ANSimport java.util.Scanner; class Bina_node { Bina_node .pdf
ANSimport java.util.Scanner; class Bina_node { Bina_node .pdfANSimport java.util.Scanner; class Bina_node { Bina_node .pdf
ANSimport java.util.Scanner; class Bina_node { Bina_node .pdfanukoolelectronics
 
All I know about rsc.io/c2go
All I know about rsc.io/c2goAll I know about rsc.io/c2go
All I know about rsc.io/c2goMoriyoshi Koizumi
 
package singlylinkedlist; public class Node { public String valu.pdf
package singlylinkedlist; public class Node { public String valu.pdfpackage singlylinkedlist; public class Node { public String valu.pdf
package singlylinkedlist; public class Node { public String valu.pdfamazing2001
 
Write a program that displays an AVL tree along with its balance fac.docx
 Write a program that displays an AVL tree  along with its balance fac.docx Write a program that displays an AVL tree  along with its balance fac.docx
Write a program that displays an AVL tree along with its balance fac.docxajoy21
 
complete the following functions in c++ singleRotation putNo.pdf
complete the following functions in c++ singleRotation putNo.pdfcomplete the following functions in c++ singleRotation putNo.pdf
complete the following functions in c++ singleRotation putNo.pdfabbecindia
 
Program of sorting using shell sort #include stdio.h #de.pdf
 Program of sorting using shell sort  #include stdio.h #de.pdf Program of sorting using shell sort  #include stdio.h #de.pdf
Program of sorting using shell sort #include stdio.h #de.pdfanujmkt
 
Data StructuresPlease I need help completing this c++ program..pdf
Data StructuresPlease I need help completing this c++ program..pdfData StructuresPlease I need help completing this c++ program..pdf
Data StructuresPlease I need help completing this c++ program..pdfarkleatheray
 
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDYDATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDYMalikireddy Bramhananda Reddy
 
mainpublic class AssignmentThree {    public static void ma.pdf
mainpublic class AssignmentThree {    public static void ma.pdfmainpublic class AssignmentThree {    public static void ma.pdf
mainpublic class AssignmentThree {    public static void ma.pdffathimafancyjeweller
 
hi i have to write a java program involving link lists. i have a pro.pdf
hi i have to write a java program involving link lists. i have a pro.pdfhi i have to write a java program involving link lists. i have a pro.pdf
hi i have to write a java program involving link lists. i have a pro.pdfarchgeetsenterprises
 
Write a C program that reads the words the user types at the command.pdf
Write a C program that reads the words the user types at the command.pdfWrite a C program that reads the words the user types at the command.pdf
Write a C program that reads the words the user types at the command.pdfSANDEEPARIHANT
 
I want help in the following C++ programming task. Please do coding .pdf
I want help in the following C++ programming task. Please do coding .pdfI want help in the following C++ programming task. Please do coding .pdf
I want help in the following C++ programming task. Please do coding .pdfbermanbeancolungak45
 
ReversePoem.java ---------------------------------- public cl.pdf
ReversePoem.java ---------------------------------- public cl.pdfReversePoem.java ---------------------------------- public cl.pdf
ReversePoem.java ---------------------------------- public cl.pdfravikapoorindia
 

Similar to in this assignment you are asked to write a simple driver program an.pdf (20)

Linked lists
Linked listsLinked lists
Linked lists
 
VTU DSA Lab Manual
VTU DSA Lab ManualVTU DSA Lab Manual
VTU DSA Lab Manual
 
This is a c++ binary search program I worked so far but still cant g.pdf
This is a c++ binary search program I worked so far but still cant g.pdfThis is a c++ binary search program I worked so far but still cant g.pdf
This is a c++ binary search program I worked so far but still cant g.pdf
 
ANSimport java.util.Scanner; class Bina_node { Bina_node .pdf
ANSimport java.util.Scanner; class Bina_node { Bina_node .pdfANSimport java.util.Scanner; class Bina_node { Bina_node .pdf
ANSimport java.util.Scanner; class Bina_node { Bina_node .pdf
 
All I know about rsc.io/c2go
All I know about rsc.io/c2goAll I know about rsc.io/c2go
All I know about rsc.io/c2go
 
Javascript
JavascriptJavascript
Javascript
 
package singlylinkedlist; public class Node { public String valu.pdf
package singlylinkedlist; public class Node { public String valu.pdfpackage singlylinkedlist; public class Node { public String valu.pdf
package singlylinkedlist; public class Node { public String valu.pdf
 
week-16x
week-16xweek-16x
week-16x
 
Write a program that displays an AVL tree along with its balance fac.docx
 Write a program that displays an AVL tree  along with its balance fac.docx Write a program that displays an AVL tree  along with its balance fac.docx
Write a program that displays an AVL tree along with its balance fac.docx
 
complete the following functions in c++ singleRotation putNo.pdf
complete the following functions in c++ singleRotation putNo.pdfcomplete the following functions in c++ singleRotation putNo.pdf
complete the following functions in c++ singleRotation putNo.pdf
 
Program of sorting using shell sort #include stdio.h #de.pdf
 Program of sorting using shell sort  #include stdio.h #de.pdf Program of sorting using shell sort  #include stdio.h #de.pdf
Program of sorting using shell sort #include stdio.h #de.pdf
 
Data StructuresPlease I need help completing this c++ program..pdf
Data StructuresPlease I need help completing this c++ program..pdfData StructuresPlease I need help completing this c++ program..pdf
Data StructuresPlease I need help completing this c++ program..pdf
 
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDYDATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
DATASTRUCTURES PPTS PREPARED BY M V BRAHMANANDA REDDY
 
Writing MySQL UDFs
Writing MySQL UDFsWriting MySQL UDFs
Writing MySQL UDFs
 
mainpublic class AssignmentThree {    public static void ma.pdf
mainpublic class AssignmentThree {    public static void ma.pdfmainpublic class AssignmentThree {    public static void ma.pdf
mainpublic class AssignmentThree {    public static void ma.pdf
 
hi i have to write a java program involving link lists. i have a pro.pdf
hi i have to write a java program involving link lists. i have a pro.pdfhi i have to write a java program involving link lists. i have a pro.pdf
hi i have to write a java program involving link lists. i have a pro.pdf
 
DS Code (CWH).docx
DS Code (CWH).docxDS Code (CWH).docx
DS Code (CWH).docx
 
Write a C program that reads the words the user types at the command.pdf
Write a C program that reads the words the user types at the command.pdfWrite a C program that reads the words the user types at the command.pdf
Write a C program that reads the words the user types at the command.pdf
 
I want help in the following C++ programming task. Please do coding .pdf
I want help in the following C++ programming task. Please do coding .pdfI want help in the following C++ programming task. Please do coding .pdf
I want help in the following C++ programming task. Please do coding .pdf
 
ReversePoem.java ---------------------------------- public cl.pdf
ReversePoem.java ---------------------------------- public cl.pdfReversePoem.java ---------------------------------- public cl.pdf
ReversePoem.java ---------------------------------- public cl.pdf
 

More from michardsonkhaicarr37

h. What are epigenetic changes How may these contribute to the deve.pdf
h. What are epigenetic changes How may these contribute to the deve.pdfh. What are epigenetic changes How may these contribute to the deve.pdf
h. What are epigenetic changes How may these contribute to the deve.pdfmichardsonkhaicarr37
 
How does alcohol affect IPSP and Potassium Why do the ions move.pdf
How does alcohol affect IPSP and Potassium Why do the ions move.pdfHow does alcohol affect IPSP and Potassium Why do the ions move.pdf
How does alcohol affect IPSP and Potassium Why do the ions move.pdfmichardsonkhaicarr37
 
How has the social change driven the development of new information t.pdf
How has the social change driven the development of new information t.pdfHow has the social change driven the development of new information t.pdf
How has the social change driven the development of new information t.pdfmichardsonkhaicarr37
 
Describe the concept of web accessibility.Thank-you!Solution.pdf
Describe the concept of web accessibility.Thank-you!Solution.pdfDescribe the concept of web accessibility.Thank-you!Solution.pdf
Describe the concept of web accessibility.Thank-you!Solution.pdfmichardsonkhaicarr37
 
Good new technologies are a bit like good new roads Their social ben.pdf
Good new technologies are a bit like good new roads Their social ben.pdfGood new technologies are a bit like good new roads Their social ben.pdf
Good new technologies are a bit like good new roads Their social ben.pdfmichardsonkhaicarr37
 
can you help me to solve this. Design a Person class similar to the .pdf
can you help me to solve this. Design a Person class similar to the .pdfcan you help me to solve this. Design a Person class similar to the .pdf
can you help me to solve this. Design a Person class similar to the .pdfmichardsonkhaicarr37
 
Cephalothorax, 6 pairs of jointed appendages. Aquatic, but comes to s.pdf
Cephalothorax, 6 pairs of jointed appendages. Aquatic, but comes to s.pdfCephalothorax, 6 pairs of jointed appendages. Aquatic, but comes to s.pdf
Cephalothorax, 6 pairs of jointed appendages. Aquatic, but comes to s.pdfmichardsonkhaicarr37
 
After reading the codes of ethics posted to the USAOnline site please.pdf
After reading the codes of ethics posted to the USAOnline site please.pdfAfter reading the codes of ethics posted to the USAOnline site please.pdf
After reading the codes of ethics posted to the USAOnline site please.pdfmichardsonkhaicarr37
 
A small boy is lost coming down Mount Washington. The leader of the .pdf
A small boy is lost coming down Mount Washington. The leader of the .pdfA small boy is lost coming down Mount Washington. The leader of the .pdf
A small boy is lost coming down Mount Washington. The leader of the .pdfmichardsonkhaicarr37
 
Address how cooperative binding contributes to SSB function during D.pdf
Address how cooperative binding contributes to SSB function during D.pdfAddress how cooperative binding contributes to SSB function during D.pdf
Address how cooperative binding contributes to SSB function during D.pdfmichardsonkhaicarr37
 
A perfect left-sided binary tree is a binary tree where every intern.pdf
A perfect left-sided binary tree is a binary tree where every intern.pdfA perfect left-sided binary tree is a binary tree where every intern.pdf
A perfect left-sided binary tree is a binary tree where every intern.pdfmichardsonkhaicarr37
 
Assembly Code Pep8 Question Write a Pep8 subroutine that is equiva.pdf
Assembly Code Pep8 Question Write a Pep8 subroutine that is equiva.pdfAssembly Code Pep8 Question Write a Pep8 subroutine that is equiva.pdf
Assembly Code Pep8 Question Write a Pep8 subroutine that is equiva.pdfmichardsonkhaicarr37
 
why might bacteria need to alter gene expression when their environm.pdf
why might bacteria need to alter gene expression when their environm.pdfwhy might bacteria need to alter gene expression when their environm.pdf
why might bacteria need to alter gene expression when their environm.pdfmichardsonkhaicarr37
 
Which of the three principles from the Belmont Report were violated .pdf
Which of the three principles from the Belmont Report were violated .pdfWhich of the three principles from the Belmont Report were violated .pdf
Which of the three principles from the Belmont Report were violated .pdfmichardsonkhaicarr37
 
Where is the cell body of the neuron that directly causes SA node ce.pdf
Where is the cell body of the neuron that directly causes SA node ce.pdfWhere is the cell body of the neuron that directly causes SA node ce.pdf
Where is the cell body of the neuron that directly causes SA node ce.pdfmichardsonkhaicarr37
 
Which of the following is FALSE regarding phylogenetic inference met.pdf
Which of the following is FALSE regarding phylogenetic inference met.pdfWhich of the following is FALSE regarding phylogenetic inference met.pdf
Which of the following is FALSE regarding phylogenetic inference met.pdfmichardsonkhaicarr37
 
What is the critical F value for a sample of four observations in th.pdf
What is the critical F value for a sample of four observations in th.pdfWhat is the critical F value for a sample of four observations in th.pdf
What is the critical F value for a sample of four observations in th.pdfmichardsonkhaicarr37
 
what is the main function and sub-functions of a penSolutions.pdf
what is the main function and sub-functions of a penSolutions.pdfwhat is the main function and sub-functions of a penSolutions.pdf
what is the main function and sub-functions of a penSolutions.pdfmichardsonkhaicarr37
 
what are some barriers a company might need to overcome when enterin.pdf
what are some barriers a company might need to overcome when enterin.pdfwhat are some barriers a company might need to overcome when enterin.pdf
what are some barriers a company might need to overcome when enterin.pdfmichardsonkhaicarr37
 
True or False1 The highest abundance of microbial life in soils .pdf
True or False1 The highest abundance of microbial life in soils .pdfTrue or False1 The highest abundance of microbial life in soils .pdf
True or False1 The highest abundance of microbial life in soils .pdfmichardsonkhaicarr37
 

More from michardsonkhaicarr37 (20)

h. What are epigenetic changes How may these contribute to the deve.pdf
h. What are epigenetic changes How may these contribute to the deve.pdfh. What are epigenetic changes How may these contribute to the deve.pdf
h. What are epigenetic changes How may these contribute to the deve.pdf
 
How does alcohol affect IPSP and Potassium Why do the ions move.pdf
How does alcohol affect IPSP and Potassium Why do the ions move.pdfHow does alcohol affect IPSP and Potassium Why do the ions move.pdf
How does alcohol affect IPSP and Potassium Why do the ions move.pdf
 
How has the social change driven the development of new information t.pdf
How has the social change driven the development of new information t.pdfHow has the social change driven the development of new information t.pdf
How has the social change driven the development of new information t.pdf
 
Describe the concept of web accessibility.Thank-you!Solution.pdf
Describe the concept of web accessibility.Thank-you!Solution.pdfDescribe the concept of web accessibility.Thank-you!Solution.pdf
Describe the concept of web accessibility.Thank-you!Solution.pdf
 
Good new technologies are a bit like good new roads Their social ben.pdf
Good new technologies are a bit like good new roads Their social ben.pdfGood new technologies are a bit like good new roads Their social ben.pdf
Good new technologies are a bit like good new roads Their social ben.pdf
 
can you help me to solve this. Design a Person class similar to the .pdf
can you help me to solve this. Design a Person class similar to the .pdfcan you help me to solve this. Design a Person class similar to the .pdf
can you help me to solve this. Design a Person class similar to the .pdf
 
Cephalothorax, 6 pairs of jointed appendages. Aquatic, but comes to s.pdf
Cephalothorax, 6 pairs of jointed appendages. Aquatic, but comes to s.pdfCephalothorax, 6 pairs of jointed appendages. Aquatic, but comes to s.pdf
Cephalothorax, 6 pairs of jointed appendages. Aquatic, but comes to s.pdf
 
After reading the codes of ethics posted to the USAOnline site please.pdf
After reading the codes of ethics posted to the USAOnline site please.pdfAfter reading the codes of ethics posted to the USAOnline site please.pdf
After reading the codes of ethics posted to the USAOnline site please.pdf
 
A small boy is lost coming down Mount Washington. The leader of the .pdf
A small boy is lost coming down Mount Washington. The leader of the .pdfA small boy is lost coming down Mount Washington. The leader of the .pdf
A small boy is lost coming down Mount Washington. The leader of the .pdf
 
Address how cooperative binding contributes to SSB function during D.pdf
Address how cooperative binding contributes to SSB function during D.pdfAddress how cooperative binding contributes to SSB function during D.pdf
Address how cooperative binding contributes to SSB function during D.pdf
 
A perfect left-sided binary tree is a binary tree where every intern.pdf
A perfect left-sided binary tree is a binary tree where every intern.pdfA perfect left-sided binary tree is a binary tree where every intern.pdf
A perfect left-sided binary tree is a binary tree where every intern.pdf
 
Assembly Code Pep8 Question Write a Pep8 subroutine that is equiva.pdf
Assembly Code Pep8 Question Write a Pep8 subroutine that is equiva.pdfAssembly Code Pep8 Question Write a Pep8 subroutine that is equiva.pdf
Assembly Code Pep8 Question Write a Pep8 subroutine that is equiva.pdf
 
why might bacteria need to alter gene expression when their environm.pdf
why might bacteria need to alter gene expression when their environm.pdfwhy might bacteria need to alter gene expression when their environm.pdf
why might bacteria need to alter gene expression when their environm.pdf
 
Which of the three principles from the Belmont Report were violated .pdf
Which of the three principles from the Belmont Report were violated .pdfWhich of the three principles from the Belmont Report were violated .pdf
Which of the three principles from the Belmont Report were violated .pdf
 
Where is the cell body of the neuron that directly causes SA node ce.pdf
Where is the cell body of the neuron that directly causes SA node ce.pdfWhere is the cell body of the neuron that directly causes SA node ce.pdf
Where is the cell body of the neuron that directly causes SA node ce.pdf
 
Which of the following is FALSE regarding phylogenetic inference met.pdf
Which of the following is FALSE regarding phylogenetic inference met.pdfWhich of the following is FALSE regarding phylogenetic inference met.pdf
Which of the following is FALSE regarding phylogenetic inference met.pdf
 
What is the critical F value for a sample of four observations in th.pdf
What is the critical F value for a sample of four observations in th.pdfWhat is the critical F value for a sample of four observations in th.pdf
What is the critical F value for a sample of four observations in th.pdf
 
what is the main function and sub-functions of a penSolutions.pdf
what is the main function and sub-functions of a penSolutions.pdfwhat is the main function and sub-functions of a penSolutions.pdf
what is the main function and sub-functions of a penSolutions.pdf
 
what are some barriers a company might need to overcome when enterin.pdf
what are some barriers a company might need to overcome when enterin.pdfwhat are some barriers a company might need to overcome when enterin.pdf
what are some barriers a company might need to overcome when enterin.pdf
 
True or False1 The highest abundance of microbial life in soils .pdf
True or False1 The highest abundance of microbial life in soils .pdfTrue or False1 The highest abundance of microbial life in soils .pdf
True or False1 The highest abundance of microbial life in soils .pdf
 

Recently uploaded

Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,Virag Sontakke
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaVirag Sontakke
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxsocialsciencegdgrohi
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfadityarao40181
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...M56BOOKSTORE PRODUCT/SERVICE
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 

Recently uploaded (20)

Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,भारत-रोम व्यापार.pptx, Indo-Roman Trade,
भारत-रोम व्यापार.pptx, Indo-Roman Trade,
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of India
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdf
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)————IMP.OF KSHARA ...
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 

in this assignment you are asked to write a simple driver program an.pdf

  • 1. in this assignment you are asked to write a simple driver program and set of functions (maybein a library) that can be performed on a binary search tree. Your program should allow user to insert/delete integer values into the binary search tree along with several other operations on the binary search tree. You can use the code given in slides. But this time your key will be int! Specifically, your program will ask user to enter a command and related parameters (if any) in a loop, and then perform the given commands. Here is the list of commands that your program must implement: * insert *find' *delete *list inorder *list preorder *list postorder *list levelorder * max * min * height *count * sum *quit As always, make sure you release (free) the dynamically allocated memories if you allocate any memory in your programs. So, before submitting your program, run it with valgrind to see if there is any memory leakage //my proggram in C struct tree_node { int data; struct tree_node *left, *right; } typedef struct nodeT { int key; struct nodeT *left, *right; } nodeT, *treeT; int main(){ while (TRUE) { printf("> ");
  • 2. line = GetLine(); ch = toupper(line[0]); switch (ch) { case 'I': insert(); break; case 'F': find(); break; case 'D': delete(); break; case 'LI': listInorder; break; case 'LPR': listPreorder(); break; case 'LPO': listPostorder(); break; case 'MAX': max(); break; case 'min': min(); break; case 'H': height(); break; case 'C': count(); break; case 'S': sum(); break; case 'Q': exit(0); default:printf("Illegal command "); break; } } } nodeT *FindNode(nodeT *t, int key){ while(t !=NULL) { if (key == t->key) return t; if (key < t->key) { t = t->left; } else { t = t->right; } return NULL; } void delete(nodeT **p){ nodeT *target; target=*p;
  • 3. if (target->left==NULL && target->right==NULL) { *p=NULL; } else if (target->left == NULL) { *p=target->right; } else if (target->right == NULL) { *p=target->left; } else { /* target has two children, see next slide */ } free(target); } void listInorder(nodeT *T){ if (t != NULL) { DisplayTree(t->left); printf(“%d “, t->key); DisplayTree(t->right); } } void listPreorder(nodeT *t) { if (t != NULL) { printf(“%d “, t->key); DisplayTree(t->left); DisplayTree(t->right); } } void listPostOrder(nodeT *t){ if (t != NULL) { DisplayTree(t->left); DisplayTree(t->right); printf(“%d “, t->key); } } void intsert(nodeT **tptr, int key){ nodeT*t, *tmp;
  • 4. t=*tptr; if (t == NULL) { tmp=New(nodeT*); tmp->key = key; tmp->left=tmp->right=NULL; *tptr=tmp; return; } if (key < t->key) { InsertNode (&t->left, key); } else { InsertNode(&t->right, key); } } int height(nodeT *t){ if (t == NULL) return 0; else return (1 + maximumof( height(t->left), height(t->right)) ); } int sum(struct tree_node *p){ if (p == NULL) return 0; else return (p->data + sum(p->left) + sum(p->right) ); } Solution 1. /*
  • 5. 2. * Java Program to Implement Binary Search Tree 3. */ 4. 5. import java.util.Scanner; 6. 7. /* Class BSTNode */ 8. class BSTNode 9. { 10. BSTNode left, right; 11. int data; 12. 13. /* Constructor */ 14. public BSTNode() 15. { 16. left = null; 17. right = null; 18. data = 0; 19. } 20. /* Constructor */ 21. public BSTNode(int n) 22. { 23. left = null; 24. right = null; 25. data = n; 26. } 27. /* Function to set left node */ 28. public void setLeft(BSTNode n) 29. { 30. left = n; 31. } 32. /* Function to set right node */ 33. public void setRight(BSTNode n) 34. { 35. right = n; 36. } 37. /* Function to get left node */
  • 6. 38. public BSTNode getLeft() 39. { 40. return left; 41. } 42. /* Function to get right node */ 43. public BSTNode getRight() 44. { 45. return right; 46. } 47. /* Function to set data to node */ 48. public void setData(int d) 49. { 50. data = d; 51. } 52. /* Function to get data from node */ 53. public int getData() 54. { 55. return data; 56. } 57. } 58. 59. /* Class BST */ 60. class BST 61. { 62. private BSTNode root; 63. 64. /* Constructor */ 65. public BST() 66. { 67. root = null; 68. } 69. /* Function to check if tree is empty */ 70. public boolean isEmpty() 71. { 72. return root == null; 73. }
  • 7. 74. /* Functions to insert data */ 75. public void insert(int data) 76. { 77. root = insert(root, data); 78. } 79. /* Function to insert data recursively */ 80. private BSTNode insert(BSTNode node, int data) 81. { 82. if (node == null) 83. node = new BSTNode(data); 84. else 85. { 86. if (data <= node.getData()) 87. node.left = insert(node.left, data); 88. else 89. node.right = insert(node.right, data); 90. } 91. return node; 92. } 93. /* Functions to delete data */ 94. public void delete(int k) 95. { 96. if (isEmpty()) 97. System.out.println("Tree Empty"); 98. else if (search(k) == false) 99. System.out.println("Sorry "+ k +" is not present"); 100. else 101. { 102. root = delete(root, k); 103. System.out.println(k+ " deleted from the tree"); 104. } 105. } 106. private BSTNode delete(BSTNode root, int k) 107. { 108. BSTNode p, p2, n; 109. if (root.getData() == k)
  • 8. 110. { 111. BSTNode lt, rt; 112. lt = root.getLeft(); 113. rt = root.getRight(); 114. if (lt == null && rt == null) 115. return null; 116. else if (lt == null) 117. { 118. p = rt; 119. return p; 120. } 121. else if (rt == null) 122. { 123. p = lt; 124. return p; 125. } 126. else 127. { 128. p2 = rt; 129. p = rt; 130. while (p.getLeft() != null) 131. p = p.getLeft(); 132. p.setLeft(lt); 133. return p2; 134. } 135. } 136. if (k < root.getData()) 137. { 138. n = delete(root.getLeft(), k); 139. root.setLeft(n); 140. } 141. else 142. { 143. n = delete(root.getRight(), k); 144. root.setRight(n); 145. }
  • 9. 146. return root; 147. } 148. /* Functions to count number of nodes */ 149. public int countNodes() 150. { 151. return countNodes(root); 152. } 153. /* Function to count number of nodes recursively */ 154. private int countNodes(BSTNode r) 155. { 156. if (r == null) 157. return 0; 158. else 159. { 160. int l = 1; 161. l += countNodes(r.getLeft()); 162. l += countNodes(r.getRight()); 163. return l; 164. } 165. } 166. /* Functions to search for an element */ 167. public boolean search(int val) 168. { 169. return search(root, val); 170. } 171. /* Function to search for an element recursively */ 172. private boolean search(BSTNode r, int val) 173. { 174. boolean found = false; 175. while ((r != null) && !found) 176. { 177. int rval = r.getData(); 178. if (val < rval) 179. r = r.getLeft(); 180. else if (val > rval) 181. r = r.getRight();
  • 10. 182. else 183. { 184. found = true; 185. break; 186. } 187. found = search(r, val); 188. } 189. return found; 190. } 191. /* Function for inorder traversal */ 192. public void inorder() 193. { 194. inorder(root); 195. } 196. private void inorder(BSTNode r) 197. { 198. if (r != null) 199. { 200. inorder(r.getLeft()); 201. System.out.print(r.getData() +" "); 202. inorder(r.getRight()); 203. } 204. } 205. /* Function for preorder traversal */ 206. public void preorder() 207. { 208. preorder(root); 209. } 210. private void preorder(BSTNode r) 211. { 212. if (r != null) 213. { 214. System.out.print(r.getData() +" "); 215. preorder(r.getLeft()); 216. preorder(r.getRight()); 217. }
  • 11. 218. } 219. /* Function for postorder traversal */ 220. public void postorder() 221. { 222. postorder(root); 223. } 224. private void postorder(BSTNode r) 225. { 226. if (r != null) 227. { 228. postorder(r.getLeft()); 229. postorder(r.getRight()); 230. System.out.print(r.getData() +" "); 231. } 232. } 233. } 234. 235. /* Class BinarySearchTree */ 236. public class BinarySearchTree 237. { 238. public static void main(String[] args) 239. { 240. Scanner scan = new Scanner(System.in); 241. /* Creating object of BST */ 242. BST bst = new BST(); 243. System.out.println("Binary Search Tree Test "); 244. char ch; 245. /* Perform tree operations */ 246. do 247. { 248. System.out.println(" Binary Search Tree Operations "); 249. System.out.println("1. insert "); 250. System.out.println("2. delete"); 251. System.out.println("3. search"); 252. System.out.println("4. count nodes"); 253. System.out.println("5. check empty");
  • 12. 254. 255. int choice = scan.nextInt(); 256. switch (choice) 257. { 258. case 1 : 259. System.out.println("Enter integer element to insert"); 260. bst.insert( scan.nextInt() ); 261. break; 262. case 2 : 263. System.out.println("Enter integer element to delete"); 264. bst.delete( scan.nextInt() ); 265. break; 266. case 3 : 267. System.out.println("Enter integer element to search"); 268. System.out.println("Search result : "+ bst.search( scan.nextInt() )); 269. break; 270. case 4 : 271. System.out.println("Nodes = "+ bst.countNodes()); 272. break; 273. case 5 : 274. System.out.println("Empty status = "+ bst.isEmpty()); 275. break; 276. default : 277. System.out.println("Wrong Entry "); 278. break; 279. } 280. /* Display tree */ 281. System.out.print(" Post order : "); 282. bst.postorder(); 283. System.out.print(" Pre order : "); 284. bst.preorder(); 285. System.out.print(" In order : "); 286. bst.inorder(); 287. 288. System.out.println(" Do you want to continue (Type y or n) "); 289. ch = scan.next().charAt(0);
  • 13. 290. } while (ch == 'Y'|| ch == 'y'); 291. } 292. }