如何从特定节点向后遍历AVL树?

时间:2019-06-13 10:00:46

标签: c++ binary-tree

我已经成功实现了等级AVL树,该树包含一个额外的字段,其中包含该节点的子树中所有键的总和(例如,对于特定节点,该节点具有sum_of_sub_tree_keys + node_key)

我想实现一种方法,该方法从特定节点返回所有更大键的总和(包括该节点键),该函数的作用是从树中的给定节点向后遍历(调用父级),并且: 1)如果节点来自该父节点的左侧,则我将父节点的密钥加上他的右子树总和相加。 2)如果节点来自该父节点的右侧,那么我不添加任何内容,我只是继续沿该路径向后移动。

最后,外部函数将节点的键添加到该函数的结果中,但似乎不起作用,有人可以告诉我我的代码有什么问题吗:

int auxSumOfMaxKeys(Node* node) {
    if (node->parent == NULL)
        return sumForNode(root->right);
    if (node->parent == root && node->parent->left == node)
        return sumForNode(root->right) + root->key;
    if (node->parent == root && node->parent->right == node)
        return sumForNode(node->right);
    if (node->parent->left == node)
        return auxSumOfMaxKeys(node->parent) + sumForNode(node->parent->right) + node->parent->key;
    if (node->parent->right == node)
        return auxSumOfMaxKeys(node->parent);
}

int sumOfMaxKeys(Node* node) {
    int node_key = node->key;
    return node_key + auxSumOfMaxKeys(node);
}

注意:这棵树完美地工作了,所有添加和父级更新都完成了,这样,我已经测试了其余部分,我很确定问题出在函数本身上。

感谢您的帮助,

谢谢

0 个答案:

没有答案