写了个tostring

This commit is contained in:
2024-11-21 23:09:02 +08:00
parent f8d136fd8e
commit fdbef4b3cc
3 changed files with 45 additions and 19 deletions
+20
View File
@@ -1,4 +1,5 @@
#include "BiTree.h"
#include <sstream>
bool BiTree::is_empty(BiTree *bt) {
if (bt == nullptr) {
@@ -43,3 +44,22 @@ void BiTree::insertNode(BiTree*& bt, int value) {
}
}
}
void toStringHelper(const BiTree *node, std::ostringstream &oss, const std::string &prefix, bool isLeft) {
if (node != nullptr) {
oss << prefix;
oss << (isLeft ? "|--" : "|--") << node->data << "\n";
std::string newPrefix = prefix + (isLeft ? "| " : " ");
toStringHelper(node->left, oss, newPrefix, true);
toStringHelper(node->right, oss, newPrefix, false);
}
}
std::string BiTree::toString() {
std::ostringstream oss;
toStringHelper(this, oss, "", false);
return oss.str();
}
+7 -1
View File
@@ -1,6 +1,7 @@
#ifndef BITREE_H
#define BITREE_H
#include<sstream>
class BiTree {
@@ -10,12 +11,17 @@ public:
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);
std::string toString();
};
#endif //BITREE_H
+3 -3
View File
@@ -1,12 +1,11 @@
/*
*二叉树采用二叉链存储结构存放,结点值为int 类型,设计一个递归算法求二叉树 bt 中所有叶子结点值之和
*二叉树采用二叉链存储结构存放,结点值为int 类型,设计一个递归算法求二叉树 bt 中所有叶子结点值之和
*/
#include<iostream>
#include"BiTree.h"
using namespace std;
BiTree *createTreeFromArray(const int *values, int size) {
BiTree *root = nullptr;
for (int i = 0; i < size; ++i) {
@@ -21,6 +20,7 @@ int main() {
BiTree *root = createTreeFromArray(testValues, size);
cout << "Sum of leaf nodes: " << BiTree::sum_leaf(root) << endl;
cout << "树结构为:" << endl << root->toString() << endl;
cout << "叶子节点之和为: " << BiTree::sum_leaf(root) << endl;
return 0;
}