我制作了一个按顺序打印树的递归函数
void print_tree(TREE_TYPE eType,Tree* root) {
if (eType == TREE_TYPE_INT)
print1(TREE_TYPE_INT, root);
if (eType == TREE_TYPE_CHAR)
print1(TREE_TYPE_INT, root);
}
void print_element(TREE_TYPE eType, void* data) {
if (eType == TREE_TYPE_INT) {
printf("(%d)", *((int*)data));
} else if (eType == TREE_TYPE_CHAR) {
printf("(%c)", *((char*)data));
}
}
void print1(TREE_TYPE eType, Tree* root) {
if (root == NULL)
return;
if (root->left) {
print1(eType, root->left);
printf("<");
}
print_element(eType, root->data);
if (root->right) {
printf(">");
print1(eType, root->right);
}
}
现在我必须按以下方式为具有 2,3,8 的树添加括号才能打印结果:((2)<(3)>(8)) 但是当将 7 添加到树中时,将其打印如下:((2)<(3)>((7)<(8)))。 就像每棵至少有一个节点的树都必须放在括号中一样。 有没有办法递归地做到这一点?
最佳答案
您可以用两个括号将 print1
函数中的代码“括起来”,并检查是否为 null,如下所示:
if (root->left || root->right) printf("(");
关于c - 打印带括号的有序二叉搜索树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28393947/