diff --git a/05-trees/BinaryTree.h b/05-trees/BinaryTree.h index d9653cc..ca72414 100644 --- a/05-trees/BinaryTree.h +++ b/05-trees/BinaryTree.h @@ -40,7 +40,8 @@ public: void inOrder(void visit(ItemType &)) const { _inorder(visit, rootPtr); } void postOrder(void visit(ItemType &)) const { _postorder(visit, rootPtr); } - // void printTree(void visit(ItemType &, int)) const{_printTree(visit, rootPtr, 1);} + + void printTree(void visit(ItemType &, int)) const { _printTree(visit, rootPtr, 1); } // abstract functions to be implemented by derived class virtual bool insert(const ItemType &newData) = 0; @@ -57,7 +58,8 @@ private: void _inorder(void visit(ItemType &), BinaryNode *nodePtr) const; void _postorder(void visit(ItemType &), BinaryNode *nodePtr) const; - // void _printTree(void visit(ItemType &, int), BinaryNode* nodePtr, int level) const; + + void _printTree(void visit(ItemType &, int), BinaryNode *nodePtr, int level) const; }; @@ -108,4 +110,15 @@ void BinaryTree::_postorder(void visit(ItemType &), BinaryNode +void BinaryTree::_printTree(void visit(ItemType &, int), BinaryNode *nodePtr, int level) const { + if (nodePtr == nullptr) return; + + ItemType item = nodePtr->getItem(); + visit(item, level); + _printTree(visit, nodePtr->getRightPtr(), level + 1); + _printTree(visit, nodePtr->getLeftPtr(), level + 1); +} + #endif diff --git a/05-trees/main.cpp b/05-trees/main.cpp index d2385c4..469a660 100644 --- a/05-trees/main.cpp +++ b/05-trees/main.cpp @@ -1,5 +1,4 @@ // BST ADT -// Smallest/Largest // Name: Iurii Tatishchev #include "BinarySearchTree.h" @@ -14,35 +13,24 @@ void hDisplay(int &); void vDisplay(int &); +void iDisplay(int &, int); int main() { BinarySearchTree bst; int n; - char option; cout << "What is the number of nodes in the BST? " << endl; cin >> n; - cout << "Find Smallest or Largest[S/L]? " << endl; - cin >> option; buildBST(n, bst); - if (n < 15) { - cout << " Inorder: "; - bst.inOrder(hDisplay); - cout << endl; - } - if (option == 'S' || option == 's') { - int minVal; - bst.findSmallest(minVal); - cout << "Smallest: " << minVal << endl; - } else if (option == 'L' || option == 'l') { - int maxVal; - bst.findLargest(maxVal); - cout << "Largest: " << maxVal << endl; - } + cout << " Inorder: "; + bst.inOrder(hDisplay); + cout << endl; + cout << "Indented Tree:" << endl; + bst.printTree(iDisplay); return 0; } @@ -72,3 +60,13 @@ void hDisplay(int &item) { void vDisplay(int &item) { cout << item << endl; } + +/* + indented tree display: one item per line, including the level number +*/ +void iDisplay(int &item, int level) { + for (int i = 1; i < level; i++) + cout << ".."; + cout << level << "). " << item << endl; + +} \ No newline at end of file