1. Without using stacks, write the functions for the following tree class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
template<typename T>
class Tree
{
T data;
Tree<T>* LBranch;
Tree<T>* RBranch;
public:
Tree() : LBranch(NULL), RBranch(NULL) {}
void FillToDepth(const T& FillWith, constunsignedlong& Depth)
{
//write code here that creates a tree to the specified depth
}
~Tree()
{
//write code here to properly clean up all memory you allocated
}
};
Instantiating a Tree<int> object and calling FillToDepth(5, 5) should have 63 total branches, including itself.
Implement an array/vector search, both linear and binary.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
template <typename T>
T find(vector<T> arr, T trg, int index = 0) {
//...
}
template <typename T>
T binSearch(vector<T> arr, T trg, int start, int end) {
//...
}
tamplate <typename T>
T binSearch(vector<T> arr, T trg) {
return binSearch(arr, trg, 0, arr.size());
}
Here's one I did a while back. Define integer addition and subtraction operations using only bitwise and comparison operators. (And of course using recursion.)
1 2 3 4
//using only = & | ^ ~ << >> == != and no for/while/goto loops
int add(int a, int b);
int subtract(int a, int b);
//(I think that's all of them...)
[A good example of recursion] is any kind of hierarchical parsing (XML, for example).
Oo. My first true need for recursion was when I made a Perl script that recursively iterated your directory structure (from some root directory) and outputted to an XML file with the information. It was sweet! (Also the XML was well formatted. I used a global variable for the leading white space.)