Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/164.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 为了遍历AVL树,将值保存在数组中_C++_Struct_Avl Tree - Fatal编程技术网

C++ 为了遍历AVL树,将值保存在数组中

C++ 为了遍历AVL树,将值保存在数组中,c++,struct,avl-tree,C++,Struct,Avl Tree,我试图按顺序(从最小值到最大值)遍历AVL树,并将值保存在数组中。我怎么能做这样的事?我被困在这个递归中,不知道如何正确地执行它,以下是我到目前为止所做的: // Called with node = root node of the AVL tree // x is the length of the array // y is 0 at the start // array is the array I want to fill void inorder(int* array,Tree_N

我试图按顺序(从最小值到最大值)遍历AVL树,并将值保存在数组中。我怎么能做这样的事?我被困在这个递归中,不知道如何正确地执行它,以下是我到目前为止所做的:

// Called with node = root node of the AVL tree
// x is the length of the array
// y is 0 at the start
// array is the array I want to fill

void inorder(int* array,Tree_Node* node,int x,int y)
{
    if(!node)
    {
        return;
    }
    inorder(array, node->getLeft(), x, y);

    array[y] = GET_ID(node->getkey());
    y++;
    if (y == x)
    {
        return;
    }
    inorder(array, node->getRight(), x, y);
} 

这里最大的问题是数组索引错误。考虑任意节点的顺序遍历。从索引
y
开始,将所有内容都写在左侧子项下。然后忽略刚才所做的操作,将当前节点的值写入索引
y
。然后,因为您总是递增
y
,所以在您检查
y==x
的点上,可能会出现
y>x
,并且您写入了越界

我强烈建议使用
std::vector
(如果需要进一步处理,其
data()
成员函数可以像数组一样使用)来解决这个问题。这也将允许您摆脱长度限制:

void inorder(Tree_Node* node, std::vector<int>& vector)
{
    if (!node) return;
    inorder(node->getLeft(), vector);

    vector.push_back(GET_ID(node->getkey()));

    inorder(node->getRight(), vector);
}

您显示的代码有什么问题?你说的“卡住”是什么意思?请,我建议你也读一读。
int inorder(int* array, Tree_Node* node, int size, int y = 0)
{
    if (!node) return y;
    y = inorder(array, node->getLeft(), size, y);

    if (y >= size) return y; /* Check before you write! */
    array[y++] = GET_ID(node->getkey());

    return inorder(array, node->getRight(), size, y);
}