#ifndef BITREE_H #define BITREE_H #include #include #include template class BiTree { public: T data; BiTree* left; BiTree* right; BiTree() : left(nullptr), right(nullptr) { } static bool is_empty(BiTree* bt) { if (bt == nullptr) { return true; } return false; } static bool is_leaf(BiTree* bt) { if (bt->left == nullptr && bt->right == nullptr) { return true; } return false; } static T sum_leaf(BiTree* bt) { if (is_empty(bt)) { return 0; } if (is_leaf(bt)) { return bt->data; } return sum_leaf(bt->left) + sum_leaf(bt->right); } static BiTree* createNode(const T& value) { BiTree* node = new BiTree(); node->data = value; node->left = nullptr; node->right = nullptr; return node; } static void insertNode(BiTree*& bt, T value) { if (bt == nullptr) { bt = createNode(value); } else { if (value < bt->data) { insertNode(bt->left, value); } if (value > bt->data) { insertNode(bt->right, value); } } } static BiTree* buildFromPreorderString(const std::string& preorder, size_t& index) { if (index >= preorder.size() || preorder[index] == '#') { index++; return nullptr; } BiTree* node = createNode(preorder[index++]); node->left = buildFromPreorderString(preorder, index); node->right = buildFromPreorderString(preorder, index); return node; } void inorderTraversal(std::ostringstream& oss) const { if (left) left->inorderTraversal(oss); oss << data; if (right) right->inorderTraversal(oss); } void toStringHelper(std::ostringstream& oss, const std::string& prefix, bool isLeft, bool hasSibling) const { if (this != nullptr) { oss << prefix; oss << (isLeft ? (hasSibling ? "├─" : "└─") : (hasSibling ? "├─" : "└─")) << data << "\n"; std::string newPrefix = prefix + (isLeft ? (hasSibling ? "│ " : " ") : " "); bool hasLeftSibling = (left != nullptr && right != nullptr); if (left) left->toStringHelper(oss, newPrefix, true, hasLeftSibling); if (right) right->toStringHelper(oss, newPrefix, false, false); } } std::string toString() const { std::ostringstream oss; this->toStringHelper(oss, "", false, false); return oss.str(); } void destroy() { if (left) { left->destroy(); delete left; } if (right) { right->destroy(); delete right; } } }; #endif // BITREE_H