完美二叉树

title

完美二叉树(Perfect Binary Tree)是指每个节点都有两个子节点,并且所有叶子节点都在同一层上的二叉树。

下面是一个简单的C语言实现完美二叉树的代码:


#include <stdio.h>
#include <stdlib.h>

typedef struct node {
    int value;
    struct node *left;
    struct node *right;
} node;

int get_height(node *root) {
    if (root == NULL) {
        return 0;
    }
    int left_height = get_height(root->left);
    int right_height = get_height(root->right);
    return 1 + (left_height > right_height ? left_height : right_height);
}

int is_perfect(node *root, int height, int level) {
    if (root == NULL) {
        return 1;
    }
    if (root->left == NULL && root->right == NULL) {
        return height == level + 1;
    }
    if (root->left == NULL || root->right == NULL) {
        return 0;
    }
    return is_perfect(root->left, height, level + 1) && is_perfect(root->right, height, level + 1);
}

node *create_node(int value) {
    node *new_node = (node *)malloc(sizeof(node));
    new_node->value = value;
    new_node->left = NULL;
    new_node->right = NULL;
    return new_node;
}

void destroy_tree(node *root) {
    if (root == NULL) {
        return;
    }
    destroy_tree(root->left);
    destroy_tree(root->right);
    free(root);
}

int main() {
    node *root = create_node(1);
    root->left = create_node(2);
    root->right = create_node(3);
    root->left->left = create_node(4);
    root->left->right = create_node(5);
    root->right->left = create_node(6);
    root->right->right = create_node(7);
    int height = get_height(root);
    int level = 0;
    if (is_perfect(root, height, level)) {
        printf("The tree is a perfect binary tree\n");
    } else {
        printf("The tree is not a perfect binary tree\n");
    }
    destroy_tree(root);
    return 0;
}
powered by Gitbook© 2023 编外计划 | 最后修改: 2023-11-24 03:37:00

results matching ""

    No results matching ""