全部完成

This commit is contained in:
2024-11-22 19:20:27 +08:00
parent 7f8acf4da1
commit 82f94bdd7c
2 changed files with 61 additions and 1 deletions
+40
View File
@@ -4,6 +4,7 @@
#include <iostream>
#include <sstream>
#include <string>
#include <unordered_map>
template <typename T>
class BiTree
@@ -17,6 +18,10 @@ public:
{
}
BiTree(char val): data(val), left(nullptr), right(nullptr)
{
}
static bool is_empty(BiTree* bt)
{
if (bt == nullptr)
@@ -96,6 +101,41 @@ public:
if (right) right->inorderTraversal(oss);
}
static BiTree* buildFromPreorderInorderString(const std::string& preorder, const std::string& inorder, int preStart,
int preEnd,
int inStart, int inEnd, std::unordered_map<char, int>& inMap)
{
if (preStart > preEnd || inStart > inEnd)
{
return nullptr;
}
char rootVal = preorder[preStart];
BiTree* root = new BiTree(rootVal);
int inRoot = inMap[rootVal];
int leftSubtreeSize = inRoot - inStart;
root->left = buildFromPreorderInorderString(preorder, inorder, preStart + 1, preStart + leftSubtreeSize,
inStart, inRoot - 1, inMap);
root->right = buildFromPreorderInorderString(preorder, inorder, preStart + leftSubtreeSize + 1, preEnd,
inRoot + 1, inEnd, inMap);
return root;
}
static int getHeight(BiTree* root)
{
if (root == nullptr)
{
return 0;
}
int leftHeight = getHeight(root->left);
int rightHeight = getHeight(root->right);
return 1 + std::max(leftHeight, rightHeight);
}
void toStringHelper(std::ostringstream& oss, const std::string& prefix, bool isLeft, bool hasSibling) const
{
if (this != nullptr)