From cbad18381e5b3b70b35f0d6bf1134e137bfd0251 Mon Sep 17 00:00:00 2001 From: Alvin Philips Date: Tue, 19 Oct 2021 05:46:56 +0530 Subject: [PATCH] Added documentation Added Documentation for the level_order_traversal() function, and implemented a print() function to display the tree to STDOUT --- .../reverse_binary_tree.cpp | 41 ++++++++++++++----- 1 file changed, 31 insertions(+), 10 deletions(-) diff --git a/operations_on_datastructures/reverse_binary_tree.cpp b/operations_on_datastructures/reverse_binary_tree.cpp index f22acb371..3bb78389a 100644 --- a/operations_on_datastructures/reverse_binary_tree.cpp +++ b/operations_on_datastructures/reverse_binary_tree.cpp @@ -82,29 +82,50 @@ class BinaryTree { BinaryTree(int data) { root = new Node(data); } void add(int data) { root = insert(data, root); } void reverse() { root = reverseBinaryTree(root); } + /** + * @brief Level order traversal of a tree consists of visiting its + * elements, top to bottom, left to right. This function performs + * level order traversal and returns the node datas as a vector. + * @details The function uses a queue to append and remove elements + * as they are visited, and then adds their children, if any. This + * ensures that the elements are visited layer-by-layer, starting + * from the root of the Tree. + * @returns vector of nodes of the tree. + */ std::vector get_level_order() { - std::vector data; + std::vector data; ///< Result vector of int if (root == NULL) { - return data; + return data; ///< Return empty vector if root is Invalid } - std::queue nodes; - nodes.push(root); + std::queue nodes; ///< Queue of the nodes in the tree + nodes.push(root); ///< Insert root into the queue while (!nodes.empty()) { - Node* temp = nodes.back(); - data.push_back(temp); - nodes.pop(); + Node* temp = nodes.back(); ///< Copy the first element + data.push_back(temp->data); ///< Add the element to the data + nodes.pop(); ///< Remove element if (temp->left != NULL) { - nodes.push(temp->left); + nodes.push(temp->left); ///< Insert left node } if (temp->right != NULL) { - nodes.push(temp->right); + nodes.push(temp->right); ///< Insert right node } - } + } /// Add nodes while Tree is not empty return data; } + /** + * @brief Prints all of the elements in the tree to stdout + * level-by-level, using the get_level_order() function. + */ + void print() { + for (int i : get_level_order()) { + std::cout << i << " "; /// Print each element in the tree + } + std::cout << "\n"; /// Print newline + } }; } // namespace reverse_binary_tree } // namespace operations_on_datastructures +static void tests() {} int main() {} \ No newline at end of file