用C++实现:已知一个二叉树(从键盘输入),分别求它的双亲结点个数和叶子结点个数
时间: 2024-03-17 15:43:52 浏览: 98
好的,我来帮你解答这个问题。
首先,我们需要从键盘输入一棵二叉树。一种常见的方法是使用递归来构建二叉树,具体实现如下:
```cpp
#include <iostream>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
// 递归构建二叉树
TreeNode* buildTree() {
int val;
cin >> val;
if (val == -1) return nullptr; // -1 表示空结点
TreeNode* root = new TreeNode(val);
root->left = buildTree();
root->right = buildTree();
return root;
}
```
上述代码中,我们通过递归从键盘输入二叉树,遇到 -1 表示空结点,返回空指针。
接下来,我们可以使用与前面相同的方法来统计双亲结点个数和叶子结点个数:
```cpp
// 统计双亲结点个数
int countParent(TreeNode* root) {
if (!root) return 0;
if (root->left || root->right) {
return countParent(root->left) + countParent(root->right) + 1;
}
return 0;
}
// 统计叶子结点个数
int countLeaf(TreeNode* root) {
if (!root) return 0;
if (!root->left && !root->right) {
return 1;
}
return countLeaf(root->left) + countLeaf(root->right);
}
int main() {
TreeNode* root = buildTree();
int parentCount = countParent(root);
int leafCount = countLeaf(root);
cout << "Parent count: " << parentCount << endl;
cout << "Leaf count: " << leafCount << endl;
return 0;
}
```
在主函数中,我们先通过 `buildTree()` 函数从键盘输入二叉树,然后分别调用 `countParent()` 和 `countLeaf()` 函数来统计双亲结点个数和叶子结点个数,并输出结果。
希望对你有所帮助!
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)