C++ C++;如何将顺序遍历的节点存储到数组中?

C++ C++;如何将顺序遍历的节点存储到数组中?,c++,arrays,inorder,C++,Arrays,Inorder,我有一个这样的顺序遍历函数 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->ke

我有一个这样的顺序遍历函数


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
    
}
我试着把根添加到数组中 当inoder类型为node时,我尝试将inoder(root->left)添加到数组中


但这些都不能满足我的需要。是否可以将交叉的节点存储到一个数组中?谢谢

正如其他人已经评论过的那样,您可以用
std::vector
替换数组声明并返回它:

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;
}
void inordercursive(节点*根,标准::向量和节点)
{
if(root==NULL)
返回;
inorderCursive(根->左,节点);//访问左子树

std::cout您可以使用
std::vector
并像打印一样将元素推回。您可以通过引用将此向量作为第二个参数传递,然后向下传递递归。您需要使用带有数组的单个变量或更好的向量将元素放入其中。这可以通过多种方式实现:将其作为函数参数,或s类成员,如果这是类中的函数,则作为静态变量。@Unlikus向量类型是什么?因为键是字符串,计数是int@DickChang向量类型应该是
std::vector
在遍历左子树之后,而不是之前,除非它是前序遍历。每个调用都会创建一个新的向量,它从堆中为push_back分配,当它返回时,被复制到当前向量中。将同一个向量传递给递归调用会更有效,并且它们都会直接添加值不需要所有的复制和分配。这只剩下最初的调用:编写第二个非递归函数,它不做任何事情,只接受根指针,声明向量并将它们传递到递归函数中,返回向量(如果减少分配很重要)
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;
}