在C中打印带有逗号和空间的二进制搜索树
我正在努力打印一个二进制搜索树,如以下输出(订购遍历):
2, 3, 6, 9
我获得的输出:
2, 3, 6, 9,
我拥有的代码:
void inorder(struct node* root)
{
if (root != NULL) {
inorder(root->left_node);
printf("%d, ", root->value);
inorder(root->right_node);
}
}
如何实现结构节点:
struct node {
int value;
struct node *left_node;
struct node *right_node;
};
我不确定如何摆脱逗号和空间最后一个元素之后的字符。
I am struggling to print a binary search tree like the below output (in-order traversal):
2, 3, 6, 9
the output I get:
2, 3, 6, 9,
The code I have:
void inorder(struct node* root)
{
if (root != NULL) {
inorder(root->left_node);
printf("%d, ", root->value);
inorder(root->right_node);
}
}
how struct node is implemented:
struct node {
int value;
struct node *left_node;
struct node *right_node;
};
I am not sure how to get rid of the comma and the space characters after the last element.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
理论是,仅当您确定要打印的叶子不是最后一个时,才必须打印
,
。因此,您需要一种方法来告诉您的节点(子树)是否包含树的“最后”叶子。一种做法的方法是创建另一个功能,该函数还需要一个参数:
The theory is that you have to print the
,
only if you are sure that the leaf you are printing is not the last one.Thus, you need a way to tell your nodes (sub-trees) whether they contain the "last" leaf of your tree. One way of doing is to create another function which takes one more parameter:
您只需要打印
,
,如果右节点不为null。考虑到这一点,将printf()
拆分为两个调用,并检查下一个节点是否为null。You only need to print a
,
if the right node is not null. With that in mind, split theprintf()
into two calls and check whether the next node is null or not.