// // Created by PC on 25-8-6. // #ifndef LINKEDBINARYTREE_H #define LINKEDBINARYTREE_H #include #include #include #include "binaryTree.h" #include "binaryTreeNode.h" template class linkedBinaryTree : public binaryTree { private: static std::deque *> nodes; binaryTreeNode* root; int tsize; static void (*visit)(binaryTreeNode* node);//存储visit static void preOrder(binaryTreeNode* node) { if (node == nullptr) return; bool isLeaf = (node->left == nullptr && node->right == nullptr); if (!isLeaf) std::cout << "("; visit(node); preOrder(node->left); preOrder(node->right); if (!isLeaf) std::cout << ")"; } static void inOrder(binaryTreeNode* node) { if (node == nullptr) return; // 对非叶子节点加括号 bool isLeaf = (node->left == nullptr && node->right == nullptr); if (!isLeaf) std::cout << "("; inOrder(node->left); visit(node); inOrder(node->right); if (!isLeaf) std::cout << ")"; } static void postOrder(binaryTreeNode* node) { if (node == nullptr) return; bool isLeaf = (node->left == nullptr && node->right == nullptr); if (!isLeaf) std::cout << "("; postOrder(node->left); postOrder(node->right); visit(node); if (!isLeaf) std::cout << ")"; } //层序遍历levelOrder,使用deque,这人好聪明! static void levelOrder(binaryTreeNode* node) { std::deque*> tmp; tmp.push_back(node); nodes.push_back(node); //开始 while (!tmp.empty()) { binaryTreeNode* current = tmp.front(); tmp.pop_front(); if (current->left != nullptr) { nodes.push_back(current->left); tmp.push_back(current->left); } if (current->right != nullptr) { nodes.push_back(current->right); tmp.push_back(current->right); } } for (binaryTreeNode* x : nodes) { std::cout << x->element; } } static void dispose(binaryTreeNode* node) { if (node == nullptr) return; dispose(node->left); dispose(node->right); std::cout << "disposing " << node->element << std::endl; delete node; } public: linkedBinaryTree() {root = nullptr;tsize = 0;} explicit linkedBinaryTree(binaryTreeNode* x ) {root = x;tsize = 1;} ~linkedBinaryTree() override {erase();} bool empty() const override {return tsize == 0;} void preOrder(void(*Ivisit) (binaryTreeNode*)) const override {visit = Ivisit; preOrder(root);} //传入的是一个函数,在private里有void (*visit)来储存函数入口,从而在遍历的时候进行操作(输出,计算等) //操作的函数是visit,即访问到该node之后进行什么操作 void inOrder(void(*Ivisit) (binaryTreeNode*)) const override{visit = Ivisit; inOrder(root);} void postOrder(void(*Ivisit) (binaryTreeNode*)) const override {visit = Ivisit; postOrder(root);} void levelOrder(void(*Ivisit) (binaryTreeNode*)) const override {visit = Ivisit; levelOrder(root);} int size() const override {return tsize;} void erase() { //postOrder(dispose); dispose(root); root = nullptr; tsize = 0; } }; template void (*linkedBinaryTree::visit)(binaryTreeNode*) = nullptr; template std::deque *> linkedBinaryTree::nodes; #endif //LINKEDBINARYTREE_H