gpt4 book ai didi

c - 以特定格式图表打印二叉搜索树。在 c

转载 作者:太空宇宙 更新时间:2023-11-04 03:33:00 24 4
gpt4 key购买 nike

我需要打印一个二叉搜索树,它应该看起来像一棵树,这意味着如果我有一棵 5,6,7 的树,打印函数将把它打印成 Example 1。 :

insert
5
insert
6
insert
7
Tree is:
5
6
7

现在假设一棵树是 4,3,7 结果应该是这样的 Example 2 :

insert
4
insert
3
insert
7
tree is:
4
3 7

有 1 个限制:它应该递归完成。

这是我试图解决这个问题的代码:

void PrintTabs(int n)
{
if(n==0)
{
return;
}
else
{
printf("\t");
PrintTabs(--n);
}
}

void PrintTree(BST* root, int level)
{
if (root==NULL)
{
return;
}
PrintTree(root->Right,++level);
PrintTabs(level);
printf("%d\n",*(int*)root->Value);
PrintTree(root->Left,++level);
}

我的 2 个主要问题是它总是向右滑动打印,所以我在两个递归调用之间移动了打印部分,这给了我一个糟糕的结果,但不知何故它有我寻找的树的格式

最佳答案

//这用于从根中找到最左边的节点(即还剩多少)。这是计算出来的,因此 root 打印在中心。

findAlignment (BST * root, int *leftMost, int leftness) {

if (root == NULL) {
return;
}

if (leftness > *leftMost) {
*leftMost = leftness;
}

findAlignment (root->left, leftMost, (leftness + 1));
findAlignment (root->right, leftMost, (leftness - 1));

}

//这使用最左边的节点信息打印树。它根据节点的级别和左侧调整光标位置以直接打印。

void PrintTree(BST* root, int leftAlignment, int level)
{
if (root==NULL)
{
return;
}

// the first printf aligns the position of cursor on the screen.
// This code may not be portable on all machines.
// see http://c-faq.com/osdep/termcap.html for details.
// This particular print moves the cursor to row: 'level' and col: 'leftAlignment * 4'.
// You can change the multiplication factor from 4 based on
// how many chars root->value will have and your other requirements to make it properly align.
// You can also multiply level by some factor, if you want to align better.
printf("\033[%d;%dH", level, leftAlignment * 4);
printf("%d",root->Value);

PrintTree(root->Left, leftAlignment - 1, level + 1);
PrintTree(root->Right, leftAlignment + 1, level + 1);
}

int leftMost = 0;
findAlignment (root, &leftMost, 0);
printf("\033[2J"); // clear screen
printTree (root, leftMost, 0);

关于c - 以特定格式图表打印二叉搜索树。在 c,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34725239/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com