以二叉链表作为二叉树的存储结构,编写用层次顺序遍历二叉树的方法,统计树中度为1 的结点个数。
时间: 2023-06-16 18:02:33 浏览: 72
编写采用二叉链表形式存储的二叉树的创建、先序、中序、后序和按层遍历的算法
5星 · 资源好评率100%
以下是用C++实现的代码:
```c++
#include <iostream>
#include <queue>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
int countDegreeOne(TreeNode* root) {
if (!root) return 0;
queue<TreeNode*> q;
q.push(root);
int count = 0;
while (!q.empty()) {
TreeNode* curr = q.front();
q.pop();
if (curr->left && !curr->right || !curr->left && curr->right) {
count++;
}
if (curr->left) {
q.push(curr->left);
}
if (curr->right) {
q.push(curr->right);
}
}
return count;
}
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 count = countDegreeOne(root);
cout << "The number of degree one nodes in the tree is: " << count << endl;
return 0;
}
```
该算法的时间复杂度为O(n),其中n是二叉树中的结点数。
阅读全文