问题描述
我在以与 tree 命令在终端中打印的方式相同的方式打印二叉搜索树时遇到了问题。这就是我的树目前正在为诸如“打印 1 * 2 + 3”之类的语句打印的方式:
|_ FUNC_NODE
|_ PRINT_NODE
| |_ +
| | |_ *
| | | |_ 1
| | | |_ 2
| | |_ 3
但它应该是这样的
|_ FUNC_NODE
|_ PRINT_NODE
|_ +
|_ *
| |_ 1
| |_ 2
|_ 3
“正确”的 C++ 代码是
void printTree(Node *node,std::string indent,bool isLeft )
{
if (!node) {return;}
std::cout << indent << "|___ " << node->value << "\n";
printTree(node->left,indent + (isLeft ? "| " : " "),true);
printTree(node->right,indent + (isLeft ? "| " : " "),false);
}
void printTree()
{
printTree(root,"",false);
}
我正在尝试用 C 编写一些等效的东西作为学习练习。这是我目前在 C 中的代码
void print_tree(struct Node *n,int level,char buf[256][256],int isLeft)
{
//If the node is NULL,backtrack
if (!n) {return;}
char temp[256];
//Print the current indention
printf(buf[level]);
//Place the current indention in a temp string
strcpy(temp,buf[level]);
//If it is a left child,add a pipe to the indention buffer
if (isLeft) {
strcat(temp,"| ");
} else { //Otherwise,a blank space
strcat(temp," ");
}
//Store the new "string" in the buffer for the next call to use
strcpy(buf[level+1],temp);
//Print the visited node
printf("|_ %s\n",numToToken(n));
//Recursive subcalls
print_tree(n->left,level + 1,buf,1);
print_tree(n->right,0);
}
void print(struct Node *n)
{
//Buffer for storing indentions
char buf[256][256] = ;
print_tree(n,0);
}
我怀疑我的缓冲区在后续调用中在当前级别被覆盖,我不确定如何解决这个问题,或者我是否应该使用不同的方法。
解决方法
当您执行“+”时,您的 C++ 代码会生成新字符串,并且参数列表按值传递,因此会创建一个新副本,无论如何它们不会在递归调用中共享。 C 代码“buf”是所有这些函数调用共享的指针。您必须分别为“左”和“右”函数调用再制作 2 个副本。 对于实践来说是可以的,但是如果人们滥用你的代码,char[] 很容易溢出。