微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何以在 Windows/Linux 中找到的“tree”命令的风格在 C 语言中漂亮的二叉搜索树?

如何解决如何以在 Windows/Linux 中找到的“tree”命令的风格在 C 语言中漂亮的二叉搜索树?

我在以与 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] = 

enter image description here

; print_tree(n,0); }

我怀疑我的缓冲区在后续调用中在当前级别被覆盖,我不确定如何解决这个问题,或者我是否应该使用不同的方法

解决方法

当您执行“+”时,您的 C++ 代码会生成新字符串,并且参数列表按值传递,因此会创建一个新副本,无论如何它们不会在递归调用中共享。 C 代码“buf”是所有这些函数调用共享的指针。您必须分别为“左”和“右”函数调用再制作 2 个副本。 对于实践来说是可以的,但是如果人们滥用你的代码,char[] 很容易溢出。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。