【问题标题】:In-order traversal of an AVL tree, saving the values in an array有序遍历 AVL 树,将值保存在数组中
【发布时间】:2018-05-19 12:29:48
【问题描述】:

我正在尝试按顺序遍历 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);
} 

【问题讨论】:

标签: c++ struct avl-tree


【解决方案1】:

这里最大的问题是你的数组索引是错误的。考虑任意节点的有序遍历。您从索引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);
}

但是,如果您必须使用数组(因为手动实现 AVL 树通常在教育中完成,并且一些教育工作者非常疯狂,要求您不要使用所有可用的功能),您仍然可以通过以下方式解决此问题从函数返回当前数组索引:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-02-09
    • 2021-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-16
    • 2018-03-24
    相关资源
    最近更新 更多