我当时正在研究Binary Search树,而关于递归的概念并不是最好的。因此,我选择使用递归来完成所有基本任务。唯一的问题是我的显示功能。我可以打印出所有带有各自根节点的节点,但不是将其打印在同一行上,而是将其打印在多行上。 输出:
我尝试使用if else语句在不为null的情况下调用左右子树,但是我仍然得到相同的输出。
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
答案 0 :(得分:0)
如果左内部节点有两个特定的外部节点并且按顺序遍历; 您可以尝试:
<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))函数。