/** ****************************************************************************** * file name : bt_driver.cpp * author : Hung Q. Ngo * description: test some tree traversal routines ****************************************************************************** */ #include #include #include // for rand() and srand() #include // for time() #include "BTree.h" using namespace std; // return random tree with n nodes BTNode* random_tree(size_t n); /* * ----------------------------------------------------------------------------- * main body: test various functions * ----------------------------------------------------------------------------- */ int main() { // first, test it with a simple expression tree 2*(4+3)-6 // the following reminds me a lot of scheme/lisp BTNode* tree = new BTNode( "-", new BTNode( "*", new BTNode("2"), new BTNode( "+", new BTNode("4"), new BTNode("3") ) ), new BTNode("6") ); levelorder_print(tree); cout << endl; inorder_print(tree); cout << endl; preorder_print(tree); cout << endl; postorder_print(tree); cout << endl; clear_tree(tree); // traverse + print a random tree for fun srand(static_cast(time(0))); tree = random_tree(10); inorder_print(tree); cout << endl; postorder_print(tree); cout << endl; preorder_print(tree); cout << endl; clear_tree(tree); return 0; } /* * ----------------------------------------------------------------------------- * create a random binary tree with n nodes and return a pointer to the root * ----------------------------------------------------------------------------- */ BTNode* random_tree(size_t n) { ostringstream oss; oss << (rand() % 100); switch (n) { case 0: return NULL; case 1: return new BTNode(oss.str()); default: size_t k = rand() % n; return new BTNode(oss.str(), random_tree(k), random_tree(n-1-k)); } }