问题描述
我有像这样的有序遍历功能
void Inorder(node *root)
{
node* array;
array = new node[arraySize];
if (root == NULL)
return;
Inorder(root->left); //visit left sub-tree
std::cout << "Word: " << root->key << std::endl
<< "Occurance: " << root->count << std::endl; //print root key and its count
Inorder(root->right); //visit right sub-tree
}
为了对它进行进一步的排序,我需要将横向的节点存储在数组中,但是我不确定我能否做到这一点。视觉上我想要这样的东西
node array[0] = transversedNode;
我尝试将root添加到数组 我试过当Inorder的类型为node
时,将Inorder(root-> left)添加到数组中但是这些都不满足我的需求。是否可以将交叉的节点存储到数组中?谢谢
解决方法
正如其他人已经评论过的那样,您可以将数组声明替换为std::vector<Node*>
并返回:
void InorderRecursive(Node *root,std::vector<Node*>& nodes)
{
if (root == NULL)
return;
InorderRecursive(root->left,nodes); //visit left sub-tree
std::cout << "Word: " << root->key << std::endl
<< "Occurance: " << root->count << std::endl; //print root key and its count
nodes.push_back(root);
InorderRecursive(root->right,nodes); //visit right sub-tree
}
std::vector<Node*> Inorder(Node *root)
{
std::vector<Node*> nodes;
InorderRecursive(root,nodes);
return nodes;
}
我添加了一个附加函数InorderRecursive
,该函数调用自身并由Inorder
调用。它具有std::vector<Node*>
引用作为附加参数。原始向量在Inorder
中构造并传递。这样,您只有一个容器,可以避免复制整个内容。