练习:假设二叉树采用二叉链存储结构(即每个结点包含数据域、左孩子指针和右孩子指针),设计一个算法,计算该二叉树中结点的总数。
假设二叉树采用二叉链存储结构(即每个结点包含数据域、左孩子指针和右孩子指针),设计一个算法,计算该二叉树中结点的总数。
出现场景
| 类型 | 示例 |
|---|---|
| 考研真题 | 计算机专业考研(如408)常考编程题 |
| 在线题库 | LeetCode、牛客网、洛谷等平台有类似变种题 |
| 面试题目 | 公司校招面试中可能出现 |
考察重点:二叉树的递归遍历思想
代码实现
int BSTree_CountNode(BSTNode_t* root)
{
if (root == NULL)
{
return 0; //空树节点数为 0
}
int n = BSTree_CountNode(root->lchild);
int m = BSTree_CountNode(root->rchild);
return n + m + 1; //左子树 + 右子树 + 当前节点
}
补全代码进行测试
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
typedef int DataType_t;
typedef struct BSTreeNode
{
DataType_t Keyval;
struct BSTreeNode *lchild;
struct BSTreeNode *rchild;
}BSTNode_t;
BSTNode_t* BSTree_Create(DataType_t KeyVal)
{
BSTNode_t *root = (BSTNode_t *)calloc(1,sizeof(BSTNode_t));
if(root == NULL){
perror("Calloc memory for the root is failed!\n");
exit(-1);
}
root->lchild = NULL;
root->rchild = NULL;
root->Keyval = KeyVal;
return root;
}
BSTNode_t* BSTree_NewNode(DataType_t KeyVal)
{
BSTNode_t *New = (BSTNode_t *)calloc(1,sizeof(BSTNode_t));
if(New == NULL){
perror("Calloc memory for the New is failed!\n");
return NULL;
}
New->lchild = NULL;
New->rchild = NULL;
New->Keyval = KeyVal;
return New;
}
bool BSTree_InsertNode(BSTNode_t* root, DataType_t KeyVal)
{
if (root == NULL) {
printf("Error: root is NULL, cannot insert %d\n", KeyVal);
return false;
}
BSTNode_t *New = BSTree_NewNode(KeyVal);
if (New == NULL) {
printf("Create NewNode Error\n");
return false;
}
BSTNode_t *Proot = root;
while (Proot != NULL) {
if (KeyVal == Proot->Keyval) {
printf("Can not Insert, duplicate value: %d\n", KeyVal);
free(New); // 避免内存泄漏
return false;
}
else if (KeyVal < Proot->Keyval) {
if (Proot->lchild == NULL) {
Proot->lchild = New;
return true;
}
Proot = Proot->lchild;
}
else {
if (Proot->rchild == NULL) {
Proot->rchild = New;
return true;
}
Proot = Proot->rchild; //
}
}
}
//中序遍历
bool BSTree_InOrder(BSTNode_t* root)
{
if(root == NULL)
{
return false;
}
BSTree_InOrder(root->lchild);
printf("KeyVal = %d\n",root->Keyval);
BSTree_InOrder(root->rchild);
return true;
}
//假设二叉树采用二叉链存储结构,设计一个算法,计算给定二叉树的结点数
int BSTree_CountNode(BSTNode_t* root)
{
if (root == NULL)
{
return 0; //空树节点数为 0
}
int n = BSTree_CountNode(root->lchild);
int m = BSTree_CountNode(root->rchild);
return n + m + 1; //左子树 + 右子树 + 当前节点
}
int main(int argc, char const *argv[])
{
// 创建根节点
BSTNode_t *root = BSTree_Create(50);
// 插入节点
int values[] = {30, 70, 20, 40, 60, 80, 35, 45};
int n = sizeof(values) / sizeof(values[0]);
printf("插入节点: ");
for (int i = 0; i < n; i++) {
printf("%d ", values[i]);
BSTree_InsertNode(root, values[i]);
}
printf("\n");
// 测试重复插入
printf("尝试插入重复值 40: ");
BSTree_InsertNode(root, 40);
printf("\n");
// 中序遍历
printf("中序遍历: ");
BSTree_InOrder(root);
printf("\n");
// 统计节点数
int count = BSTree_CountNode(root);
printf("树中总节点数: %d\n", count);
return 0;
}
输出结果


浙公网安备 33010602011771号