我正在创建一个由不同节点组成的树。节点包含int元素,Node * leftchild和Node * rightchild。我想将结构存储在一个字符串中。
节点* root = NULL;
void print2DUtil(Node * tree, int space)
{
// Base case
if(root == NULL)
{
cout<<endl<<"AVL is empty."<<endl;
return;
}
if(tree == NULL)
return;
// Increase distance between levels
space += COUNT;
// Process right child first
print2DUtil(tree->rc, space);
// Print current node after space
// count
printf("\n");
for(int i = COUNT; i < space; i++)
printf(" ");
printf("%d\n", tree->data);
// Process left child
print2DUtil(tree->lc, space);
}
这是我在打印树时工作正常的代码。但是,我想将整个事物存储在一个字符串中然后打印出来。想象一下,已经存在一棵树,因为我有一个插入功能,它也可以很好地工作。
我自己尝试过,你可以纠正它或提出建议吗?
string print2DUtil(Node * tree, int space)
{
// Base case
if(root == NULL)
{
return "AVL is empty.";
}
if(tree == NULL)
return "";
// Increase distance between levels
string str = "";
space += COUNT;
// Process right child first
str = print2DUtil(tree->rc, space);
// Print current node after space
// count
str += "\n";
for(int i = COUNT; i < space; i++)
str += " ";
str += std::to_string(tree->data);
str += "\n";
// Process left child
str += print2DUtil(tree->lc, space);
return str;
}