我正在研究二叉搜索树,我对递归的概念并不是最好的。所以我选择使用递归来完成所有基本任务。唯一的问题是我的显示功能。我可以打印出所有节点及其各自的根节点,但不是在同一行上打印,而是在多行上打印。 输出:
我尝试使用 if else 语句在不为空时调用左子树和右子树,但我仍然得到相同的输出。
node_tree *display(node_tree *ref, int spaces){
if (ref==NULL)
return ref;
spaces = spaces/2;
for(int j = 0 ; j< spaces; j++)
printf(" ");
printf("%d\n", ref->data);
//display(ref->left, spaces);
//printf("\n");
//printf("%d", ref->data);
//display(ref->right, spaces);new after this line
if (ref->left!=NULL&&ref->right!=NULL){
display(ref->right, 3*spaces); display(ref->left, spaces);
}
else if(ref->right ==NULL){
display(ref->left, spaces);
}
else if(ref->left ==NULL){
display(ref->right, 3*spaces);
}
//else
//printf("%d\n", ref->data);
}
输出
12
13
10
11
9
预期输出
12
10 13
9 11
最佳答案
如果左内部节点有两个特定的外部节点并且中序遍历; 你可以尝试一下:
<code>
int node_height(node* node)
{
int u, v;
if (node == NULL)
return -1;
u = node_height(node->left);
v = node_height(node->right);
if (u > v)
return u + 1;
else
return v + 1;
}
void node_print(char* ch, int height)
{
int i;
for (i = 0; i < height; i++)
printf(" ");
printf("%c", ch);
}
void node_show(node* node, int height)
{
if (node == NULL) {
node_print('*', node_height(node));
return;
}
node_show(node->right, node_height(node) + 1);
node_print(node->item, node_height(node));
node_show(node->left, node_height(node) + 1);
}
</code>
调用给定高度的node_show(node, node_height(node))函数。
关于c - 如何水平显示我的二叉树?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58467448/