【问题标题】:C++ | Print tree (not necessarily binary) in a pretty way to stdoutC++ |以漂亮的方式将树(不一定是二进制)打印到标准输出
【发布时间】:2020-04-17 21:24:26
【问题描述】:

假设我有一个这样的struct

    struct Node {
        int val = 0;
        std::vector<Node *> _children{};
    };

如何以整洁漂亮的方式将其打印到stdout?例如像tree 程序打印目录结构的方式。

parent/
├── child1
│   ├── cchild1
│   ├── cchild2
│   ├── child3
│   │   └── child1
│   └── child4
│       ├── child1
│       └── child2
└── child2
    └── cchild1
        └── ccchild1

它不必完全按照上面的格式,因为我在这里没有偏好。

这个问题与this 不同,因为我想漂亮地打印一棵有多个孩子的树。

【问题讨论】:

  • 如何以整洁美观的方式将其打印到标准输出? -- 这不是一个重点问题。您到底遇到了什么问题,您尝试过什么,等等?
  • 您仍然可以使用this。您只需将 ifs 放置在 rightleft 中,并使用一个遍历 _children 的 for 循环。
  • 只需递归跟踪当前深度的节点并根据深度使用合适的前缀打印它们。究竟是什么问题?您尝试了哪些方法,但效果如何?

标签: c++ algorithm tree


【解决方案1】:

通过修改this answer 中的代码,我设法使其适用于具有多个孩子的树

void Node::printSubtree(const std::string &prefix) {
    using std::cout;
    using std::endl;
    if (_children.empty()) return;
    cout << prefix;
    size_t n_children = _children.size();
    cout << (n_children > 1 ? "├── " : "");

    for (size_t i = 0; i < n_children; ++i) {
        Node *c = _children[i];
        if (i < n_children - 1) {
            bool printStrand = n_children > 1 && !c->_children.empty();
            std::string newPrefix = prefix + (printStrand ? "│\t" : "\t");
            std::cout << val << "\n";
            c->printSubtree(newPrefix);
        } else {
            cout << (n_children > 1 ? prefix : "") << "└── ";
            std::cout << val << "\n";
            c->printSubtree(prefix + "\t");
        }
    }
}

void Node::printTree() {
    using std::cout;
    std::cout << val << "\n";
    printSubtree("");
    cout << "\n";
}

但是,我们欢迎新的解决方案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-16
    • 2018-10-08
    • 2013-05-27
    • 2011-01-20
    • 2011-01-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多