我需要的是在向量中推送二叉树并在终端中写出向量的内容以证明它是有效的。
我似乎无法使其发挥作用,我尝试了几种不同的方式,比如制作能为我做这些功能的功能。我是一名计算机科学专业的学生,所以我有点初学,我努力了,但我不知道该怎么做。
你通过你的帖子和答案给了我很多好的建议但是,我没有找到这方面的任何内容,所以我请求你的帮助。
这是我的二叉树:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <math.h>
using namespace std;
class Binfa {
public:
int value;
Binfa *left;
Binfa *right;
int depth() {
int leftd = 0, rightd = 0;
if (left == NULL && right == NULL)
return 1;
if (left != NULL)
leftd = left->depth();
if (right != NULL)
rightd = right->depth();
return (max(leftd, rightd) + 1);
}
static double averagedepth(Binfa *node) {
static int db = 0, sum = 0, depth = 0;
if (node != NULL) {
++depth;
Binfa::averagedepth(node->right);
Binfa::averagedepth(node->left);
--depth;
if (node->left == NULL && node->right == NULL) {
++db;
sum += depth;
}
} else {
return 0.0;
}
return (double) sum / db;
}
static double spread(Binfa *node, double average) {
static int db = 0, depth = 0;
static double sum = 0.0;
if (node != NULL) {
++depth;
spread(node->right, average);
spread(node->left, average);
--depth;
if (node->right == NULL && node->left == NULL) {
++db;
sum += ((depth - average) * (depth - average));
}
}
if (db > 1)
return sqrt(sum / (db - 1));
return sqrt(sum);
}
static void print(Binfa *node) {
static int idepth = 0;
if (node != NULL) {
++idepth;
print(node->right);
for (int i = 0; i < idepth; ++i)
printf("---");
printf("%c(%d)\n",
node->value < 2 ? '0' + node->value : node->value,
idepth - 1);
print(node->left);
--idepth;
}
}
};
int main(int argc, char **argv) {
char b;
int in = 0;
int i, egy_e;
Binfa *root = new Binfa();
root->value = '/';
root->left = root->right = NULL;
Binfa *current = root;
if (argv[1] != NULL) {
in = open(argv[1], O_RDONLY);
}
while (read(in, (void *) &b, 1)) {
for (i = 0; i < 8; ++i) {
egy_e = b & 0x80;
if ((egy_e >> 7) == 1) {
if (current->right == NULL) {
current->right = new Binfa();
current->right->value = 1;
current->right->left = current->right->right = NULL;
current = root;
} else {
current = current->right;
}
} else {
if (current->left == NULL) {
current->left = new Binfa();
current->left->value = 0;
current->left->left = current->left->right = NULL;
current = root;
} else {
current = current->left;
}
}
b <<= 1;
}
}
printf("\n");
Binfa::print(root);
printf("melyseg=%d\n", root->depth() - 1);
printf("altag=%f\n", Binfa::averagedepth(root));
printf("szoras=%f\n", Binfa::spread(root, Binfa::averagedepth(root)));
return 0;
}