二叉树功能函数 BinTree.cpp

///
//    //
//   主函数 index.cpp  用户菜单 //
//    //
//


#include <iostream.h>
#include"BaseFun.h"

void main()
{
//功能菜单
do
{
cout<<"欢迎使用数据结构算法集"<<endl
<<"1) 线性表 "<<endl
<<"2) 堆栈 "<<endl
<<"3) 队列 "<<endl
<<"4) 二叉树 "<<endl
<<"5) 图 "<<endl
<<"6) 排序算法 "<<endl
<<"7) 字符串 "<<endl
<<"X) 按任意键退出 "<<endl;
  cout<<" 请您选择何种数据结构的操作:"<<endl;
int kind;
cin>>kind;
switch(kind)
{
case 1: LIST(); break;
case 2: STACK(); break;
case 3: QUEUE(); break;
case 4: BINTREE(); break;
case 5: GRAPH(); break;
case 6: COMPOSITOR(); break;
default: return;
}
}while(true);

}
在 "BinTree.h" 中声明 `BinTreeNumNode` 函数,可以像下面这样写: ```c #ifndef BINTREE_H #define BINTREE_H typedef struct TreeNode { int val; struct TreeNode* left; struct TreeNode* right; } TreeNode; int BinTreeNumNode(const TreeNode* root); #endif /* BINTREE_H */ ``` 其中,`BinTreeNumNode` 函数的声明如下: ```c int BinTreeNumNode(const TreeNode* root); ``` 在 "BinTree.c" 中实现 `BinTreeNumNode` 函数,可以像下面这样写: ```c #include "BinTree.h" #include <stdlib.h> int BinTreeNumNode(const TreeNode* root) { if (root == NULL) { return 0; } return 1 + BinTreeNumNode(root->left) + BinTreeNumNode(root->right); } // 创建一棵二叉树 TreeNode* create_tree() { TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode)); root->val = 1; root->left = (TreeNode*)malloc(sizeof(TreeNode)); root->left->val = 2; root->right = (TreeNode*)malloc(sizeof(TreeNode)); root->right->val = 3; root->left->left = NULL; root->left->right = NULL; root->right->left = (TreeNode*)malloc(sizeof(TreeNode)); root->right->left->val = 4; root->right->right = (TreeNode*)malloc(sizeof(TreeNode)); root->right->right->val = 5; root->right->left->left = NULL; root->right->left->right = NULL; root->right->right->left = NULL; root->right->right->right = NULL; return root; } // 销毁一棵二叉树 void destroy_tree(TreeNode* root) { if (root == NULL) { return; } destroy_tree(root->left); destroy_tree(root->right); free(root); } ``` 其中,`BinTreeNumNode` 函数的实现和之前给出的一样。 另外,为了测试 `BinTreeNumNode` 函数,我们在 "BinTree.c" 中实现了创建一棵二叉树函数 `create_tree` 和销毁一棵二叉树函数 `destroy_tree`。 可以通过如下代码进行测试: ```c #include "BinTree.h" #include <stdio.h> int main() { // 构造一棵二叉树 TreeNode* root = create_tree(); // 计算结点个数 int num = BinTreeNumNode(root); // 输出结果 printf("The number of nodes is: %d\n", num); // 释放内存 destroy_tree(root); return 0; } ``` 注意:在 "BinTree.c" 中引用了 "BinTree.h",因此需要通过编译器将 "BinTree.c" 和 "BinTree.h" 编译成一个可执行文件。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值