假设二叉树中每个结点值为单个字符,采用二叉链存储结构存储设计,一个算法计算一棵树给定二叉树BT中的所有单分支结点个数.用c++
时间: 2024-03-25 20:42:06 浏览: 113
设二叉树采用链式存储结构,试设计一个算法计算一颗给定二叉树叶子节点的数目
5星 · 资源好评率100%
好的,下面是该算法的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是二叉树中节点的数量。
阅读全文