完全模板化

This commit is contained in:
2024-11-22 18:09:17 +08:00
parent aff7b6b84e
commit 89152214b3
2 changed files with 73 additions and 10 deletions
+50
View File
@@ -17,6 +17,37 @@ public:
{ {
} }
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) static BiTree* createNode(const T& value)
{ {
BiTree* node = new BiTree(); BiTree* node = new BiTree();
@@ -26,6 +57,25 @@ public:
return node; 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) static BiTree* buildFromPreorderString(const std::string& preorder, size_t& index)
{ {
if (index >= preorder.size() || preorder[index] == '#') if (index >= preorder.size() || preorder[index] == '#')
+20 -7
View File
@@ -3,15 +3,15 @@
*/ */
#include <iostream> #include <iostream>
#include "BiTree.h" #include "BiTree.h"
using namespace std; using namespace std;
BiTree<int>* createTreeFromArray(const int* values, int size)
BiTree* createTreeFromArray(const int* values, int size)
{ {
BiTree* root = nullptr; BiTree<int>* root = nullptr;
for (int i = 0; i < size; ++i) for (int i = 0; i < size; ++i)
{ {
BiTree::insertNode(root, values[i]); BiTree<int>::insertNode(root, values[i]);
} }
return root; return root;
} }
@@ -21,9 +21,22 @@ int main()
int testValues[] = {7, 3, 10, 1, 5, 9, 12}; int testValues[] = {7, 3, 10, 1, 5, 9, 12};
int size = sizeof(testValues) / sizeof(testValues[0]); int size = sizeof(testValues) / sizeof(testValues[0]);
BiTree* root = createTreeFromArray(testValues, size); BiTree<int>* root = createTreeFromArray(testValues, size);
if (root)
{
cout << "树结构为:" << endl;
cout << root->toString() << endl;
cout << "叶子节点数据总和: " << BiTree<int>::sum_leaf(root) << endl;
root->destroy();
delete root;
}
else
{
cout << "树为空。" << endl;
}
cout << "树结构为" << endl << root->toString() << endl;
cout << "叶子节点数据总和: " << BiTree::sum_leaf(root) << endl;
return 0; return 0;
} }