构建一个不完整的二叉树

Building an incomplete binary tree

我正在尝试根据文本文件中提供的数据构建一个不完整的二叉树

2
3 8
2 10 0 12
1 8 0 0 4 0

这将形成这样的树:

我大概知道我需要做什么,我想:

我 运行 遇到的问题是,我不确定如何存储指向节点的指针数组,每次调用构建函数时节点的大小都会发生变化,并且是 class 变量(对于树 class)。我这样做是对的吗?有没有更简单的方法来解决这个问题?

为什么不使用 std::vector 而不是数组?它的行为与数组完全一样,但可以调整大小。

用法示例:

using namespace std;
Node *a = new Node;
vector<Node*> vec;
vec.push_back(a);

与二维数组一样,array[row][column],您可以使用 2D vector 即。 vector< vector<int> > V 是向量的向量。

vector< vector<int> > V中,内部向量表示行,外部向量表示列(for your understanding I just tell)

此处二维矢量可以调整大小。不必每个列大小都相等。您可以处理 push, pop 并且可以根据您的内存大小存储数据。

示例:

您可以这样调整大小:

int num_of_col = 5;
int num_of_row = 9;
double init_value = 3.14;

vector< vector<double> > matrix;
//now we have an empty 2D-matrix of size (0,0). Resizing it with one single command:
matrix.resize( num_of col , vector<double>( num_of_row , init_value ) );
// and we are good to go ... 

你可以在这里学习vector