【问题标题】:Store tree data structure to an array using inorder transversal in C使用C中的中序横向将树数据结构存储到数组中
【发布时间】:2021-06-26 07:47:41
【问题描述】:

我正在尝试编写代码以使用中序横向遍历树数据结构并将每个节点存储到数组中。

我想出了下面的代码来实现它,如果代码错误,请纠正我。即使这是正确的,也必须有比使用 'static' 更好的方法来做到这一点,这会使 'index' 留在内存中直到程序完成。

void *inorderTransversal(AVLTreeNode *node, int treeSize)
{
    static int index = 0;
    AVLTreeNode *nodesArray[treeSize-1]; 
    if (node == NULL)
        return;

    inorderTransversal(node->left, treeSize);
    nodesArray[index] = node;
    index++;
    inorderTransversal(node->right, treeSize);
}

【问题讨论】:

    标签: c pointers data-structures tree


    【解决方案1】:

    您可以根据树的大小声明一个数组并存储它。

    int[treeSize] array = new int[treeSize]; 
    int index = 0; 
    void *inorderTransversal(AVLTreeNode *node) { 
        if (node == null) 
            return; 
        inorderTransversal(node->left); 
        array[index++] = node.value; 
        inorderTransversal(node->right); 
    } 
    

    【讨论】:

    • 有没有办法在函数内部包含索引?
    • @BobbyLi,没有,为什么函数内部需要它?
    • 因为我希望 index 成为本地值。
    猜你喜欢
    • 2021-06-27
    • 1970-01-01
    • 2021-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多