用括号打印树C ++

时间:2019-03-10 18:07:20

标签: c++ pointers vector printing tree

我有如下代码

// 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{} 

1 个答案:

答案 0 :(得分: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--;
    }
    }
}