diff --git a/homework4/BiTree.h b/homework4/BiTree.h index 7065f5f..3abc165 100644 --- a/homework4/BiTree.h +++ b/homework4/BiTree.h @@ -4,6 +4,7 @@ #include #include #include +#include template 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& 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) diff --git a/homework4/test3.cpp b/homework4/test3.cpp index 8af4a80..9112372 100644 --- a/homework4/test3.cpp +++ b/homework4/test3.cpp @@ -17,5 +17,25 @@ using namespace std; int main() { + int n; + cout << "请输入节点个数:"; + cin >> n; + + string preorder, inorder; + cout << "请输入前置索引:" << endl; + cin >> preorder; + cout << "请输入后置索引:" << endl; + cin >> inorder; + + std::unordered_map inMap; + for (int i = 0; i < inorder.size(); ++i) + { + inMap[inorder[i]] = i; + } + + BiTree* root = BiTree::buildFromPreorderInorderString(preorder, inorder, 0, n - 1, 0, n - 1, inMap); + + cout << "树高为:" << BiTree::getHeight(root) << endl; + cout << "该数结构为:" << endl << root->toString() << endl; return 0; -} \ No newline at end of file +}