Menu
CoddyTech

获取平衡因子

Coddy AVL 树:数据结构系列 #10 课程的第 6 课,共 16 课。

节点的平衡因子是 getHeight(node.left) - getHeight(node.right)。正数表示左侧较高,负数表示右侧较高,0 表示两侧一样高。

只要节点的平衡因子是 -1、0 或 1,就认为它是平衡的。超出这个范围(2 或更大,或 -2 或更小)就会触发旋转。

challenge icon

挑战

入门

在 AVLTree 上编写一个方法 getBalance(node),如果 node 为 null,则返回 0,否则返回 getHeight(node.left) - getHeight(node.right)。

亲手试试

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "avltree.h"

static Node* mkNodeWithHeight(int h) {
    Node* n = Node_create(0);
    n->height = h;
    return n;
}

int main(void) {
    AVLTree* tree = AVLTree_create();
    char line[256];
    while (fgets(line, sizeof(line), stdin) != NULL) {
        line[strcspn(line, "\r\n")] = '\0';
        char lTok[64];
        char rTok[64];
        sscanf(line, "%63s %63s", lTok, rTok);
        Node* root = Node_create(0);
        root->left = NULL;
        if (strcmp(lTok, "null") != 0) {
            root->left = mkNodeWithHeight(atoi(lTok));
        }
        root->right = NULL;
        if (strcmp(rTok, "null") != 0) {
            root->right = mkNodeWithHeight(atoi(rTok));
        }
        printf("%d\n", AVLTree_getBalance(tree, root));
    }
    return 0;
}

AVL 树:数据结构系列 #10中的所有课

自己练习: C 在线编译器