我正在重新发布我的问题(显然信息不足)。我想在 C 中水平打印给定的二叉树,并在节点之间有链接。 我已经在没有链接的情况下完成了;当我尝试用链接来做这件事时,它真的搞砸了。
PS:更多说明见图片Click here to view这是我使用的结构:
typedef struct node{
int val; // value of the node
struct node *left; // left node
struct node *right; // right node
}node;
这是我编写的函数,可以绘制带有空白且节点之间没有链接的树:
#define space 5
//secondary function
void draw_tree_hor2(node *tree, int distance)
{
// stopping condition
if (tree== NULL)
return;
// increase spacing
distance += space;
// start with right node
draw_tree_hor2(tree->right, distance);
// print root after spacing
printf("\n");
for (int i = space; i < distance; i++)
printf(" ");
printf("%d\n", tree->value);
// go to left node
draw_tree_hor2(tree->left, distance);
}
//primary fuction
void draw_tree_hor(node *tree)
{
//initial distance is 0
draw_tree_hor2(tree, 0);
}
如果我提供的信息不够,请告诉我...
最佳答案
我很快就把一些东西组合在一起,看起来很有效。可能需要添加一些检查以防止深度
超过路径
大小等。至少应该让您开始。
#include <stdio.h>
#define space 5
typedef struct node{
int value; // value of the node
struct node *left; // left node
struct node *right; // right node
}node;
//secondary function
void draw_tree_hor2(node *tree, int depth, char *path, int right)
{
// stopping condition
if (tree== NULL)
return;
// increase spacing
depth++;
// start with right node
draw_tree_hor2(tree->right, depth, path, 1);
if(depth > 1)
{
// set | draw map
path[depth-2] = 0;
if(right)
path[depth-2] = 1;
}
if(tree->left)
path[depth-1] = 1;
// print root after spacing
printf("\n");
for(int i=0; i<depth-1; i++)
{
if(i == depth-2)
printf("+");
else if(path[i])
printf("|");
else
printf(" ");
for(int j=1; j<space; j++)
if(i < depth-2)
printf(" ");
else
printf("-");
}
printf("%d\n", tree->value);
// vertical spacers below
for(int i=0; i<depth; i++)
{
if(path[i])
printf("|");
else
printf(" ");
for(int j=1; j<space; j++)
printf(" ");
}
// go to left node
draw_tree_hor2(tree->left, depth, path, 0);
}
//primary fuction
void draw_tree_hor(node *tree)
{
// should check if we don't exceed this somehow..
char path[255] = {};
//initial depth is 0
draw_tree_hor2(tree, 0, path, 0);
}
node n1, n2, n3, n4, n5, n6, n7;
int main()
{
n1.value = 1;
n2.value = 2;
n3.value = 3;
n4.value = 4;
n5.value = 5;
n6.value = 6;
n7.value = 7;
n1.right = &n2;
n1.left = &n3;
//n2.right = &n4;
//n2.left = &n5;
n3.right = &n6;
n3.left = &n7;
n2.right = &n3;
n2.left = &n3;
draw_tree_hor(&n1);
return 0;
}
输出:
>gcc test_graph.c && a
+----6
|
+----3
| |
| +----7
|
+----2
| |
| | +----6
| | |
| +----3
| |
| +----7
|
1
|
| +----6
| |
+----3
|
+----7
关于c - 如何使用 c 在控制台中水平打印带有链接的树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41091382/