首页 > 解决方案 > C ++如何将顺序遍历的节点存储到数组中?

问题描述

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


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; 

我尝试将根添加到数组中当 Inorder 的类型为节点时,我尝试将 Inorder(root->left) 添加到数组

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

标签: c++arraysinorder

解决方案


正如其他人已经评论的那样,您可以用 an 替换您的数组声明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并传递。这样你就有了一个容器,以避免复制整个东西。


推荐阅读