Files
data-structures-and-algorithms/homework4/BiTree.h
T
2024-11-22 17:55:29 +08:00

87 lines
2.1 KiB
C++

#ifndef BITREE_H
#define BITREE_H
#include <iostream>
#include <sstream>
#include <string>
template <typename T>
class BiTree
{
public:
T data;
BiTree* left;
BiTree* right;
BiTree() : left(nullptr), right(nullptr)
{
}
static BiTree* createNode(const T& value)
{
BiTree* node = new BiTree();
node->data = value;
node->left = nullptr;
node->right = nullptr;
return node;
}
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