请你以程序员的身份用C++语言编写可以运行的统计二叉树中结点个数和叶子结点个数的算法
时间: 2023-11-27 07:54:15 浏览: 76
好的,以下是用C++语言编写的统计二叉树中结点个数和叶子结点个数的算法:
```c++
#include<iostream>
using namespace std;
//定义二叉树结点
struct TreeNode{
int val; //结点值
TreeNode* left; //左子节点指针
TreeNode* right; //右子节点指针
TreeNode(int x):val(x),left(NULL),right(NULL){} //结构体构造函数
};
//统计二叉树结点个数的函数
int countNodes(TreeNode* root){
if(root == NULL) return 0; //如果根节点为空,返回0
return 1 + countNodes(root->left) + countNodes(root->right); //递归求取左右子树结点个数并加上当前结点,返回总结点个数
}
//统计二叉树叶子结点个数的函数
int countLeaves(TreeNode* root){
if(root == NULL) return 0; //如果根节点为空,返回0
if(root->left == NULL && root->right == NULL) return 1; //如果当前节点为叶子结点,返回1
return countLeaves(root->left) + countLeaves(root->right); //递归求取左右子树叶子结点个数并返回总叶子结点个数
}
int main(){
//构建如下二叉树
/*
1
/ \
2 3
/ \ / \
4 5 6 7
*/
TreeNode* root = new TreeNode(1);
root->left = new TreeNode(2);
root->right = new TreeNode(3);
root->left->left = new TreeNode(4);
root->left->right = new TreeNode(5);
root->right->left = new TreeNode(6);
root->right->right = new TreeNode(7);
//测试统计二叉树结点个数的函数
int node_num = countNodes(root);
cout<<"二叉树结点个数为:"<<node_num<<endl;
//测试统计二叉树叶子结点个数的函数
int leaf_num = countLeaves(root);
cout<<"二叉树叶子结点个数为:"<<leaf_num<<endl;
return 0;
}
```
运行结果:
```
二叉树结点个数为:7
二叉树叶子结点个数为:4
```
以上就是本题的C++实现,希望对您有所帮助!
阅读全文