[英]Printing a binary search tree with commas and spaces in C
I am struggling to print a binary search tree like the below output (in-order traversal):我正在努力打印如下所示的二叉搜索树 output (按顺序遍历):
2, 3, 6, 9
the output I get: output 我得到:
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.我不知道如何摆脱最后一个元素后的逗号和空格字符。
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:
一种方法是创建另一个 function ,它需要一个参数:
static void inorder_haslastleaf(struct node* root, int haslastleaf) {
if (root != NULL) {
/* Print the left sub-tree, we are guaranteed it can't contain the last leaf
* because the current node will be printed right after. */
inorder_haslastleaf(root->left_node, 0);
printf("%d", root->value);
/* Now, we have to print comma if and only if we are sure that
* some nodes will be printed after it. We can make sure of that
* thanks to the haslastleaf flag. */
if(!haslastleaf || root->right_node != NULL)
printf(", ");
/* Finally, print the right sub-tree. Pass back haslastleaf to it
* to notify whether it contains the last leaf or not */
inorder_haslastleaf(root->right_node, haslastleaf);
}
}
void inorder(struct node* root)
{
/* Of course, the main tree contains the last leaf */
inorder_haslastleaf(root, 1);
}
You only need to print a ,
if the right node is not null.如果正确的节点不是 null
,
则只需打印一个。 With that in mind, split the printf()
into two calls and check whether the next node is null or not.考虑到这一点,将
printf()
拆分为两个调用并检查下一个节点是否为 null。
void inorder(struct node* root)
{
if (root != NULL) {
inorder(root->left_node);
printf("%d", root->value);
if (root->right_node)
printf(", ");
inorder(root->right_node);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.