全部完成
This commit is contained in:
@@ -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)
|
||||
|
||||
Reference in New Issue
Block a user