可以用队列,也可以用数组的方式实现.这里我图方便,用的数组
void printNode(treeNode* rootNode) {//当前设置最多打印5层
if (!rootNode)return;
treeNode** fatherArr = new treeNode * [128]{};//每打印完一个父亲数组换行,子数*2,为空的位置也打印出来
treeNode** sonArr = new treeNode * [128]{};
cout << "-----------" << rootNode->data << "-----------" << endl;
if (rootNode->left_son) {
fatherArr[0] = rootNode->left_son;
}if (rootNode->right_son) {
fatherArr[1] = rootNode->right_son;
}
if (rootNode->left_son == nullptr && rootNode->right_son == nullptr)return;
size_t sonCountMax = 4;
size_t fatherCount = 2;
/*for (size_t i = 0; i < 2; ++i) {
if (fatherArr[i]) {
cout << fatherArr[i]->data << "\t";
}
else {
cout << "空\t";
}
}*/
int reverse = 0; size_t nullCount = 0;
size_t sonArrcount = 0;
while (true) {
sonArrcount = 0;
//不是最后一层,father<->son,儿子数组元素分裂儿子到父亲数组(每一次反转)相互转化
nullCount = 0;
if (reverse%2) {
for (size_t i = 0; i < fatherCount; ++i) {
if (sonArr[i]) {
cout << sonArr[i]->data << "\t";
if (sonArr[i]->left_son) {
fatherArr[sonArrcount] = sonArr[i]->left_son;
}
else {
fatherArr[sonArrcount] = nullptr;
}
++sonArrcount;
if (sonArr[i]->right_son) {
fatherArr[sonArrcount] = sonArr[i]->right_son;
}
else {
fatherArr[sonArrcount] = nullptr;
}
++sonArrcount;
}
else {
cout << " - ";
fatherArr[sonArrcount] = nullptr;
++sonArrcount;
fatherArr[sonArrcount] = nullptr;
++sonArrcount;
}
}
for (size_t i = 0; i < sonCountMax; ++i) {
if (fatherArr[i] == nullptr) {
++nullCount;
}
}
}
else {
for (size_t i = 0; i < fatherCount; ++i) {
if (fatherArr[i]) {
cout << fatherArr[i]->data << "\t";
if (fatherArr[i]->left_son) {
sonArr[sonArrcount] = fatherArr[i]->left_son;
}
else {
sonArr[sonArrcount] = nullptr;
}
++sonArrcount;
if (fatherArr[i]->right_son) {
sonArr[sonArrcount] = fatherArr[i]->right_son;
}
else {
sonArr[sonArrcount] = nullptr;
}
++sonArrcount;
}
else {
cout << " - ";
sonArr[sonArrcount] = nullptr;
++sonArrcount;
sonArr[sonArrcount] = nullptr;
++sonArrcount;
}
}for (size_t i = 0; i < sonCountMax; ++i) {
if (sonArr[i] == nullptr) {
++nullCount;
}
}
}++reverse;
cout << endl;
if (nullCount == sonCountMax) {
cout << "已是最后一层" << endl;
return;
}
if (sonCountMax>=128||fatherCount>=128) {
cout << "已超出打印层数限制" << endl;
return;
}
else {
sonCountMax = sonCountMax << 1;
fatherCount = fatherCount << 1;
}
}
}
来源:CSDN
作者:贰月红
链接:https://blog.csdn.net/weixin_37520565/article/details/104614616