简体   繁体   English

使用 C 中的顺序横向将树数据结构存储到数组

[英]Store tree data structure to an array using inorder transversal in C

I am trying to write a code to transverse a tree data structure using inorder transversal and store each node onto an array.我正在尝试编写代码以使用中序横向遍历树数据结构并将每个节点存储到数组中。

I came up with this code below to achieve it, please correct me if the code is wrong.我想出了下面的代码来实现它,如果代码错误,请纠正我。 Even if this is correct, there must be better ways of doing this than using 'static' which makes 'index' stayed in the memory until the program finishes.即使这是正确的,也必须有比使用'static'更好的方法来做到这一点,这使得'index'在程序完成之前一直留在memory中。

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);
}

You can declare an array based on tree size and store it.您可以根据树的大小声明一个数组并存储它。

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); 
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM