帮我用c语言写个完全二叉树问题
时间: 2023-06-11 17:08:55 浏览: 113
好的,以下是一个使用 C 语言实现的完全二叉树问题示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
typedef struct TreeNode {
int data;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;
// 创建二叉树节点
TreeNode* createNode(int value) {
TreeNode* node = (TreeNode*) malloc(sizeof(TreeNode));
node->data = value;
node->left = NULL;
node->right = NULL;
return node;
}
// 创建完全二叉树
TreeNode* createCompleteBinaryTree(int* arr, int index, int size) {
TreeNode* root = NULL;
if (index < size) {
root = createNode(arr[index]);
root->left = createCompleteBinaryTree(arr, 2*index+1, size);
root->right = createCompleteBinaryTree(arr, 2*index+2, size);
}
return root;
}
// 获取完全二叉树的高度
int getHeight(TreeNode* root) {
if (root == NULL) {
return 0;
}
int leftHeight = getHeight(root->left);
int rightHeight = getHeight(root->right);
return fmax(leftHeight, rightHeight) + 1;
}
// 获取完全二叉树的所有节点数
int getNodeCount(TreeNode* root) {
if (root == NULL) {
return 0;
}
return getNodeCount(root->left) + getNodeCount(root->right) + 1;
}
int main() {
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int size = sizeof(arr) / sizeof(arr[0]);
TreeNode* root = createCompleteBinaryTree(arr, 0, size);
int height = getHeight(root);
int nodeCount = getNodeCount(root);
printf("Complete binary tree height: %d\n", height);
printf("Complete binary tree node count: %d\n", nodeCount);
return 0;
}
```
这个程序创建一个完全二叉树,并且计算它的高度和节点数,并输出结果。
阅读全文