第二题初步完成

This commit is contained in:
2024-11-22 17:16:02 +08:00
parent f8b03bad55
commit 7037512838
4 changed files with 86 additions and 2 deletions
+35
View File
@@ -60,6 +60,29 @@ void BiTree::insertNode(BiTree*& bt, int value)
}
}
BiTree* BiTree::build_from_preorder_string(const std::string& preorder, size_t& index)
{
if (index >= preorder.size() || preorder[index] == '#')
{
index++;
return nullptr;
}
BiTree* node = createNode(preorder[index++] - 'A' + 1);
node->left = build_from_preorder_string(preorder, index);
node->right = build_from_preorder_string(preorder, index);
return node;
}
void BiTree::inOrder(std::ostringstream& oss) const
{
if (this == nullptr) return;
if (left)left->inOrder(oss);
oss << static_cast<char>(data + 'A' - 1);
if (right)right->inOrder(oss);
}
void toStringHelper(const BiTree* node, std::ostringstream& oss, const std::string& prefix, bool isLeft,
bool hasSibling)
@@ -85,3 +108,15 @@ std::string BiTree::toString()
return oss.str();
}
void BiTree::destory()
{
if (left)
{
left->destory();
}
if (right)
{
right->destory();
}
}
+3 -2
View File
@@ -2,7 +2,6 @@
#define BITREE_H
#include<sstream>
class BiTree
{
public:
@@ -10,13 +9,15 @@ public:
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();
};
+4
View File
@@ -6,3 +6,7 @@ set(CMAKE_CXX_STANDARD 20)
add_executable(test1 test1.cpp
BiTree.cpp
BiTree.h)
add_executable(test2 test2.cpp
BiTree.cpp
BiTree.h
)
+44
View File
@@ -0,0 +1,44 @@
/*
* 以字符串的形式定义一棵二叉树的先序序列,若字符是‘#’, 表示该二叉树是空树,否则该字符是相应结点的数据元素。读入相应先序序列,建立二叉链式存储结构的二叉树,然后中序遍历该二叉树并输出结点数据。
* 输入格式:
* 字符串形式的先序序列(即结点的数据类型为单个字符)
* 输出格式:
* 中序遍历结果
* 输入样例:
* 在这里给出一组输入。例如:
* ABC##DE#G##F###
* 输出样例:
* CBEGDFA
*/
#include <iostream>
#include "BiTree.h"
using namespace std;
int main()
{
string input;
cout << "请输入二叉树的先序序列(如ABC##DE#G##F###):";
cin >> input;
size_t index = 0;
BiTree* root = BiTree::build_from_preorder_string(input, index);
ostringstream oss;
if (root)
{
root->inOrder(oss);
cout << "中序遍历结果:" << oss.str() << endl;;
root->destory();
delete root;
}
else
{
cout << "输入的二叉树为空" << endl;
}
//cout << "该树结构为:" << endl;
//cout << root->toString() << endl;
return 0;
}