二叉树输出叶子结点及叶子结点个数源代码
时间: 2023-08-02 19:12:11 浏览: 190
下面是二叉树输出叶子结点及叶子结点个数的源代码(C++实现):
```cpp
#include <iostream>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
int countLeaf(TreeNode* root) {
if (root == NULL) { // 如果根节点为空,则叶子结点个数为0
return 0;
} else if (root->left == NULL && root->right == NULL) { // 如果当前节点为叶子结点,则叶子结点个数为1
return 1;
} else {
return countLeaf(root->left) + countLeaf(root->right); // 否则,叶子结点个数为左子树和右子树的叶子结点个数之和
}
}
void printLeaf(TreeNode* root) {
if (root == NULL) { // 如果根节点为空,则直接返回
return;
}
if (root->left == NULL && root->right == NULL) { // 如果当前节点为叶子结点,则输出其值
cout << root->val << " ";
} else {
printLeaf(root->left); // 否则,递归遍历左子树
printLeaf(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);
// 输出叶子结点个数
cout << "叶子结点个数为:" << countLeaf(root) << endl;
// 输出叶子结点值
cout << "叶子结点值为:";
printLeaf(root);
cout << endl;
return 0;
}
```
运行结果:
```
叶子结点个数为:4
叶子结点值为:4 5 6 7
```
阅读全文