打印二进制搜索树与缩进

时间:2016-03-29 17:50:21

标签: c++ printing traversal inorder

我试图打印我的BST,使其打印成这样:

        50, 11
               45,72
40,12
               30,16
        20,16
               10,54

我的代码不是我想要的,但在这里它是:

 void AVLTree::printHelp(Node * node)
    {
        if (node == 0) {
            return;
        }   
        printHelp(node->left);

        indent = "";
        for (size_t i = 1; i < calculateHeight(node); i++)
        {
            indent += "     ";
        }

        cout << '\n' << indent << node->value;
        printHelp(node->right);

    }

1 个答案:

答案 0 :(得分:1)

您的代码至少存在两个问题:

  1. 要查看树,您需要向左倾斜。因此,您应该首先打印子项,然后是节点,然后是 left 子项。

  2. 通过重新计算缩进的节点高度,您可以平算此操作的复杂性。

  3. 尝试这样的事情:

        newLastName = lastName.toUpperCase();
        System.out.println(newLastName);
    

    调用
    #include <string>
    
    void AVLTree::printHelp(const Node *const node, size_t height)
    {
        if (node == 0) {
            return;
        }   
    
        printHelp(node->right, height + 1);
        cout << string(height, ' ')  << node->value << endl;
        printHelp(node->left, height + 1);
    }