请用c++实现求二叉树的叶结点
时间: 2023-12-06 12:39:34 浏览: 81
以下是使用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);
TreeNode* node1 = new TreeNode(2);
TreeNode* node2 = new TreeNode(3);
TreeNode* node3 = new TreeNode(4);
TreeNode* node4 = new TreeNode(5);
root->left = node1;
root->right = node2;
node1->left = node3;
node1->right = node4;
//求叶结点数并输出
int leafNodesCount = countLeafNodes(root);
cout << "The number of leaf nodes in the binary tree is: " << leafNodesCount << endl;
return 0;
}
```
在这个程序中,我们首先定义了一个二叉树结点 `TreeNode`,包括结点值、左右子树指针等成员变量。接着,我们定义了一个 `countLeafNodes` 函数,用于递归求解二叉树的叶结点数。在函数中,我们判断当前结点是否为空或者是否为叶结点,如果是,则返回1,否则递归求解其左右子树的叶结点数并相加。最后,我们在 `main` 函数中构造了一棵二叉树,调用 `countLeafNodes` 函数求解叶结点数并输出结果。
阅读全文