A. [50] A toy that many children play with is a base with three pegs and five di
ID: 3537197 • Letter: A
Question
A. [50] A toy that many children play with is a base with three pegs and five disks of different
diameters. The disks begin on one peg, with the largest disk on the bottom and the other four
disks added on in order of size. The idea is to move the disks from the peg they are on to another
peg by moving only one disk at a time and without ever putting a larger disk on top of a smaller
one. This child's toy is actually an example of a classic mathematical puzzle called the Towers of
Hanoi problem.
Write a recursive solution to this problem. It may take you a while to see the solution, but the
program itself is quite short.
Consider the source peg is A, the temporary peg is B, and the destination peg is C.
Sample Input/output
Enter number of disks: 1
Solution: A%u2192C
Enter number of disks: 2
Solution: A%u2192B A%u2192C B%u2192C
Enter number of disks: 3
Solution: A%u2192C A%u2192B C%u2192B A%u2192C B%u2192A B%u2192C A%u2192C
Upload in the URCourses
The source code (Assignment3PartA.CPP)
B. [50] Create a Binary Search Tree of integer values, then implement the operations:
(i) Traverse Inorder
(ii) Traverse Preorder
(iii)Traverse Postorder
(iv)Insert a new item (if the same item already exists, give a message %u201Calready
exists%u201D)
(v) Delete an item (if the item does not exists, give a message %u201Citem not found%u201D)
Assumption: Each item in the BST is unique.
Explanation / Answer
//PART A
//Will post part B Soon
#include <iostream>
#include <string>
using namespace std;
void hanoi(int n, string source, string destination, string help) {
if (n == 1) {
cout<<source<< "->" << destination << " ";
} else {
hanoi(n - 1, source, help, destination);
cout << source << "->" << destination << " ";
hanoi(n - 1, help, destination, source);
}
}
int main() {
int disks;
cout << "Enter number of disks:";
cin >> disks;
hanoi(disks, "A", "C", "B");
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.