C++二叉树叶结点个数
时间: 2023-06-14 10:08:32 浏览: 133
计算二叉树叶子结点个数可以通过递归的方式进行。如果当前节点为空,则返回0;如果当前节点的左右子节点都为空,则说明当前节点为叶子节点,返回1;否则,递归计算左子树和右子树的叶子节点个数,并将它们相加返回。
以下是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 countLeafNodes(TreeNode* root) {
if (root == NULL) {
return 0;
}
if (root->left == NULL && root->right == NULL) {
return 1;
}
return countLeafNodes(root->left) + countLeafNodes(root->right);
}
int main() {
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 count = countLeafNodes(root);
cout << "Leaf nodes count: " << count << endl;
return 0;
}
```
输出结果为:
```
Leaf nodes count: 4
```
阅读全文