我试图以更易读的方式打印二叉树,而不是仅仅排成一行。我使用this question的答案作为开头,但是从左到右打印数据如下:
25
15
10
20
30
35
我需要它看起来像这样:
25
15 30
10 20 35
这是我的代码:
void printTree(AVLNode* root, int indent)
{
if (root != nullptr) {
if (indent) {
cout << setw(indent) << ' ';
}
cout << root->data << endl;
if (root->left) printTree(root->left, indent + 4);
if (root->right) printTree(root->right, indent + 4);
}
}
关于如何让它以我想要的方式打印的任何想法?
答案 0 :(得分:1)
考虑以下示例
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
// .... your code ....
void buildTree(AVLNode* root, int scrWidth, int itemWidth)
// breadth-first traversal with depth limit based on screen width and output field width for one elemet
{
bool notFinished = false;
// check the root
if (root)
{
notFinished = true;
}
// calculate maximum possible depth
int depth = 1;
int field = scrWidth;
while (field > itemWidth)
{
depth++;
field /= 2;
}
// check result
if (depth < 1)
{
cout << " -= erroneous output options =-" << endl;
return;
}
AVLNode** pItems = new AVLNode*[1];
*pItems = root; // pointer to item on the first level
int itemCnt = 1;
int divWidth = 1;
// loop for output not more than depth levels until the data is not finished
// where level is current depth of tree, and root is on the first level
for (int level = 1; level <= depth && notFinished; level++)
{
itemCnt = (level == 1) ? 1 : (itemCnt * 2);
divWidth *= 2;
// make list of pointers to refer items on next level
AVLNode** list = new AVLNode*[itemCnt * 2];
// output all utems of that level
int nextCnt = 0;
notFinished = false;
for (int i = 0; i < itemCnt; i++, nextCnt += 2)
{
int curWidth = (scrWidth / divWidth) * ((i > 0) ? 2 : 1);
cout << setw((curWidth>=itemWidth) ? curWidth:(itemWidth/(1+(i==0))));
if (pItems[i])
{
cout << pItems[i]->data;
list[nextCnt] = pItems[i]->left;
list[nextCnt + 1] = pItems[i]->right;
if (list[nextCnt] || list[nextCnt + 1])
notFinished = true;
}
else
{
cout << ".";
list[nextCnt] = NULL;
list[nextCnt + 1] = NULL;
}
}
cout << endl;
// free the memory allocated for list of pointers
if (pItems)
delete[] pItems;
pItems = list; // and shift to new one (for next level)
}
delete[] pItems;
}
int main(int argc, char* argv[])
{
// create some structure
AVLNode * root = NULL;
// code for making tree
// ....
buildTree(root, 80, 5);
// some other code
// ....
return 0;
}
调用buildTree(root, 80, 5);
打印树状(其中.
表示NULL而不是item):
64
58 .
24 62 . .
0 78 . . . . . .
41 69 . . . . . . . . . . . . . .
但buildTree(root, 40, 10);
会输出相同的数据
64
58 .
24 62 . .
即。只有三层,因为第四层有8个项目,如果每个要求10个字符总重量40是不够的。
注意:我没有足够的时间来调试代码并使其完美,但我希望它能帮助您找到自己的解决方案。