用C++语言求一棵二叉树中每层叶节点的数目,要求: 编写函数 LeafInEachLevel(root),其中:root是指向二叉树根节点的指针; 该函数的功能是,输出以root为根的二叉树中每层的叶节点数目。
时间: 2024-03-09 22:46:15 浏览: 57
好的,以下是用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) {}
};
vector<int> LeafInEachLevel(TreeNode* root) {
vector<int> res;
if (!root) return res;
queue<TreeNode*> q{{root}};
int level = 0, leafCount = 0, nextLevelCount = 1;
while (!q.empty()) {
auto node = q.front(); q.pop();
if (!node->left && !node->right) ++leafCount;
if (node->left) q.push(node->left);
if (node->right) q.push(node->right);
if (--nextLevelCount == 0) {
res.push_back(leafCount);
leafCount = 0;
++level;
nextLevelCount = q.size();
}
}
return res;
}
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);
vector<int> res = LeafInEachLevel(root);
for (int i = 0; i < res.size(); ++i) {
cout << "Level " << i << " leaf count: " << res[i] << endl;
}
return 0;
}
```
这个函数的时间复杂度也是O(n),其中n是二叉树中节点的个数。
阅读全文