【问题标题】:Printing a tree with brackets C++ [closed]用括号 C++ 打印一棵树 [关闭]
【发布时间】:2019-03-10 18:07:20
【问题描述】:

我有如下代码

// Example program
#include <iostream>
#include <string>
#include <vector>


struct Node{
    std::string name;
    Node * parent;
    std::vector<Node *> children;
};

void storeOutput(Node * nod, std::string &str)
{
    str += nod->name;
    str += "{";
    if(nod->children.size() > 0){
        for(auto &n : nod->children){
            storeOutput(n, str);
            str += "}";
        }
    }
}

int main()
{
  // Create nodes
  Node * root = new Node();
  root->name = "root";
  Node * child1 = new Node();
  child1->name = "child1";
  Node * child2 = new Node();
  child2->name = "child2";
  Node * child3 = new Node();
  child3->name = "child1.1";

  // Set parents
  root->parent = nullptr;
  child1->parent = root;
  child2->parent = root;
  child3->parent = child1;

  // Assign children
  std::vector<Node *> rootChildren;
  rootChildren.push_back(child1);
  rootChildren.push_back(child2);
  root->children = rootChildren;
  std::vector<Node *> child1Children;
  child1Children.push_back(child3);
  child1->children = child1Children;

  // Print nodes
  std::string output;
  Node * node = root;
  storeOutput(node, output);
  std::cout << output;

}

如何将这棵树从根节点开始打印成以下格式的字符串:

root 
{ 
    child1
    { 
        child1.1 
        { 
        } 
    } 
    child2 
    { 
    } 
}

我了解执行此操作的方法与存储节点的树遍历有关,但我不确定如何实现这些。

我现在正在打印列表,但它缺少一个结束括号。

root{child1{child1.1{}}child2{} 

【问题讨论】:

  • 你的问题是什么?
  • @Yunnosch 我想知道如何以格式打印出树
  • 基本上是问“满足我要求的代码是什么?”的问题。太宽泛了。
  • 你可以手写你的例子,所以你必须有一个算法;这是什么?
  • 请为您最好的代码创建一个minimal reproducible example。不管你有什么。您确实有一些东西至少可以打印向量中的所有条目并且只缺少适当的缩进,不是吗?显示。然后显示输出并描述你不喜欢它的地方。如果你连这样的东西都没有,那么请理解 StackOverflow 不是免费的代码编写服务。

标签: c++ pointers vector printing tree


【解决方案1】:

好的,我重写你的输出函数。它看起来很粗糙,但很有效

 void storeOutput (Node * nod, std::string & str, int p)
{
  p++;

  for (int x = 0; x < p; x++)
  {
    str += "  ";
  }

  str += nod->name;



  str += "\n";

  for (int x = 0; x < p; x++)
  {
    str += "  ";
  }

  str += "{ \n";
  if (nod->children.size () > 0)
    {
    for (auto & n:nod->children)
    {
      storeOutput (n, str, p);

      for (int x = 0; x < p + 1; x++)
      {
        str += "  ";
      }

      str += "} \n";

      p--;
    }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-11
    • 1970-01-01
    • 2010-10-15
    • 2014-05-07
    • 2021-12-11
    相关资源
    最近更新 更多