假设二叉树中每个结点值为单个字符,采用二叉链存储结构存储设计,一个算法计算一棵树给定二叉树BT中的所有单分支结点个数.用c++
时间: 2024-03-25 12:42:06 浏览: 118
数据结构与算法-实验五 huffman树
好的,下面是该算法的C++代码实现:
```c++
#include <iostream>
using namespace std;
struct TreeNode {
char val;
TreeNode* left;
TreeNode* right;
TreeNode(char x) : val(x), left(nullptr), right(nullptr) {}
};
int countSingleBranchNodes(TreeNode* root) {
if (!root) {
return 0;
}
int count = 0;
if (root->left && !root->right) {
count += 1;
} else if (root->right && !root->left) {
count += 1;
}
count += countSingleBranchNodes(root->left) + countSingleBranchNodes(root->right);
return count;
}
int main() {
// 构造一棵二叉树
TreeNode* root = new TreeNode('A');
root->left = new TreeNode('B');
root->right = new TreeNode('C');
root->left->left = new TreeNode('D');
root->left->right = new TreeNode('E');
root->right->left = new TreeNode('F');
root->right->right = new TreeNode('G');
root->left->left->left = new TreeNode('H');
root->left->left->right = new TreeNode('I');
root->left->right->left = new TreeNode('J');
root->right->right->left = new TreeNode('K');
root->right->right->right = new TreeNode('L');
int count = countSingleBranchNodes(root);
cout << "单分支结点的个数为:" << count << endl;
return 0;
}
```
这个算法的时间复杂度是O(n),其中n是二叉树中节点的数量。
阅读全文