c++ 中求二叉树中度为2的结点以及叶子结点的数目
时间: 2024-05-08 11:15:00 浏览: 97
求二叉树中度为2的结点数目:
```c
int countTwoDegreeNode(TreeNode* root) {
if (root == NULL) {
return 0;
}
if (root->left != NULL && root->right != NULL) {
return countTwoDegreeNode(root->left) + countTwoDegreeNode(root->right) + 1;
} else {
return countTwoDegreeNode(root->left) + countTwoDegreeNode(root->right);
}
}
```
求二叉树中叶子结点数目:
```c
int countLeafNode(TreeNode* root) {
if (root == NULL) {
return 0;
}
if (root->left == NULL && root->right == NULL) {
return 1;
} else {
return countLeafNode(root->left) + countLeafNode(root->right);
}
}
```
相关问题
写代码,用c++先用先序遍历构建二叉树,再求二叉树的叶子结点数目和度为二的结点数目
以下是代码实现:
```c++
#include <iostream>
using namespace std;
struct TreeNode {
char val;
TreeNode* left;
TreeNode* right;
TreeNode(char x) : val(x), left(nullptr), right(nullptr) {}
};
// 构建二叉树,输入先序遍历序列
TreeNode* buildTree() {
char ch;
cin >> ch;
if (ch == '#') {
return nullptr;
}
TreeNode* root = new TreeNode(ch);
root->left = buildTree();
root->right = buildTree();
return root;
}
// 计算二叉树叶子节点数目和度为二的节点数目
void count(TreeNode* root, int& leafCount, int& degree2Count) {
if (!root) {
return;
}
if (!root->left && !root->right) {
leafCount++;
} else if (root->left && root->right) {
degree2Count++;
}
count(root->left, leafCount, degree2Count);
count(root->right, leafCount, degree2Count);
}
int main() {
TreeNode* root = buildTree();
int leafCount = 0;
int degree2Count = 0;
count(root, leafCount, degree2Count);
cout << "叶子节点数目:" << leafCount << endl;
cout << "度为二的节点数目:" << degree2Count << endl;
return 0;
}
```
输入示例:
```
AB#D##CE##F##
```
输出结果:
```
叶子节点数目:3
度为二的节点数目:2
```
c++编程实现:求二叉树的高度和叶子结点个数
#include <iostream>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
int getHeight(TreeNode* root) {
if (root == NULL) return 0;
int leftHeight = getHeight(root->left);
int rightHeight = getHeight(root->right);
return max(leftHeight, rightHeight) + 1;
}
int getLeafCount(TreeNode* root) {
if (root == NULL) return 0;
if (root->left == NULL && root->right == NULL) return 1;
return getLeafCount(root->left) + getLeafCount(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 height = getHeight(root);
int leafCount = getLeafCount(root);
cout << "The height of the binary tree is: " << height << endl;
cout << "The number of leaf nodes in the binary tree is: " << leafCount << endl;
return 0;
}
阅读全文