改成模板类了
This commit is contained in:
+75
-13
@@ -1,24 +1,86 @@
|
||||
#ifndef BITREE_H
|
||||
#define BITREE_H
|
||||
#include<sstream>
|
||||
|
||||
#include <iostream>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
|
||||
template <typename T>
|
||||
class BiTree
|
||||
{
|
||||
public:
|
||||
int data;
|
||||
T data;
|
||||
BiTree* left;
|
||||
BiTree* right;
|
||||
|
||||
static bool is_empty(BiTree* bt);
|
||||
static bool is_leaf(BiTree* bt);
|
||||
static int sum_leaf(BiTree* bt);
|
||||
static BiTree* createNode(int data);
|
||||
static void insertNode(BiTree*& bt, int value);
|
||||
static BiTree* build_from_preorder_string(const std::string& preorder, size_t& index);
|
||||
void inOrder(std::ostringstream& oss) const;
|
||||
std::string toString();
|
||||
void destory();
|
||||
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
|
||||
#endif // BITREE_H
|
||||
|
||||
Reference in New Issue
Block a user