如何以这种格式使用递归绘制 BST?

How to draw BST with recursion in this format?

本文关键字:递归 绘制 BST 格式      更新时间:2023-10-16
void printGivenLevel(node *root, int level, int side, int x, int y)
{
if(root == NULL)
return;
if(level == 1)
{
gotoxy(x, y);
cout << root->data;
}
else if(level > 1)
{
if(y<=2)
{
printGivenLevel(root->left, level-1, 1, x-4, y);
printGivenLevel(root->right,level-1, 2, x+4, y);
}
else
{
printGivenLevel(root->left, level-1, 1, x-2, y);
printGivenLevel(root->right,level-1, 2, x+2, y);
}
}
}
void print(node *root)
{
int h = height(root);
int i;
int side = 0; // Use 1 for left and 2 for right 
int x = 42; //42 is the center of console
for(i=1;i<=h;i++)
{
printGivenLevel(root, i, side, x, i);
cout << endl;
}
}

我正在使用 c++,需要像这样的输出 BST .上面的代码只能格式化到级别 1。我还没有包括下划线,因为我试图先修复空格。我正在寻找一种方法来格式化它,而无需使用队列等太复杂的东西,我也在使用 turbo c++ 任何帮助将不胜感激。谢谢

由于您在撰写此答案时未能提供 MCVE,因此我只是自己制作。

从您的问题中,我认为您的主要问题是使递归正常工作。我在此答案中提供的代码应该可以让您深入了解如何解决这个问题。

仍然有一个缺点:树的每个节点都打印在单独的行上。


法典:

#include <iostream>
#include <memory>
#include <string>
struct Node
{
Node(Node* l, Node* r, std::string d) : left(l), right(r), data(d) {}
std::unique_ptr<Node> left;
std::unique_ptr<Node> right;
std::string data;
};
void printTree(Node& root, int minx, int maxx)
{
auto x = ((minx + maxx) / 2);
auto o = ((x - minx) / 2);
auto w = std::string(x - o, ' ');
auto u = std::string(o, '_');
std::cout << w << u << root.data << u << std::endl;
if (root.left != nullptr)
printTree(*(root.left), minx, x);
if (root.right != nullptr)
printTree(*(root.right), x, maxx);  
}
int main()
{
auto lrll = new Node{ nullptr, nullptr, "1" };
auto lrlr = new Node{ nullptr, nullptr, "2" };
auto lll = new Node{ nullptr, nullptr, "3" };
auto llr = new Node{ nullptr, nullptr, "4" };
auto lrl = new Node{ lrll, lrlr, "5" };
auto lrr = new Node{ nullptr, nullptr, "6" };
auto ll = new Node{ lll, llr, "7" };
auto lr = new Node{ lrl, lrr, "8" };
auto rl = new Node{ nullptr, nullptr, "9" };
auto rr = new Node{ nullptr, nullptr, "10" };
auto l = new Node{ ll, lr, "11" };
auto r = new Node{ rl, rr, "12" };
auto root = std::make_unique<Node>(l, r, "13");
printTree(*root, 0, 84);
return 0;
}

输出:

_____________________13_____________________
__________11__________
_____7_____
__3__
__4__
_____8_____
__5__
_1_
_2_
__6__
__________12__________
_____9_____
_____10_____

注意:并非所有下划线都完美对齐,因为84被选为初始最大值(我这样做是为了在位置42处获得根)。

任何二叉树都可以通过根据以下公式正确选择初始最小值和最大值,以最紧凑的方式完美表示:

max - min == 2^(h)h == 树的高度

对于我的代码中使用的树(高度为 5),完美的表示需要:

max - min == 2^(5) == 32

因此,使用任何相差 32 的最小值和最大值调用printTree()将生成树的完美且最紧凑的表示形式。例如,按如下方式调用它

printTree(*root, 0, 32)

结果为以下输出:

________13________
____11____
__7__
_3_
_4_
__8__
_5_
1
2
_6_
____12____
__9__
__10__