加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
2749.cpp 1.81 KB
一键复制 编辑 原始数据 按行查看 历史
张宬浩 提交于 2021-11-09 11:41 . add the problems of tree
#include <iostream>
#include <queue>
typedef struct BiNode{
int data;
BiNode *LChild;
BiNode *RChild;
}BiNode,*BiTree;
void initTree(BiTree &tree);
void getTree(BiTree &tree);
unsigned int getLeafCount(BiNode* node);
int main() {
// the number of test sets
int T = 0;
std::cin >> T;
for (int i = 0; i < T; i++) {
BiTree tree = new BiNode;
initTree(tree);
getTree(tree);
std::cout << getLeafCount(tree) << std::endl;
}
}
// Initialize the tree
void initTree(BiTree &tree) {
tree->data = 0;
tree->LChild = 0;
tree->RChild = 0;
}
// get the tree nodes in level order
void getTree(BiTree &tree) {
int key = 0;// Use the key to access each data
std::cin >> key;
// First get the data of the root
tree->data = key;
BiNode* node = tree;
std::queue<BiNode*> que;
que.push(node);
// Get each data of the leftchild and rightchild
// If it is not 0, push into the queue
// Otherwise, make it point to NULL
while(!que.empty()) {
node = que.front();
node->LChild = new BiNode;
node->RChild = new BiNode;
que.pop();
std::cin >> key;
if(key != 0){
que.push(node->LChild);
node->LChild->data = key;
}
else if (key == 0) {
node->LChild = NULL;
}
std::cin >> key;
if(key != 0){
que.push(node->RChild);
node->RChild->data = key;
}
else if (key == 0) {
node->RChild = NULL;
}
}
std::cin>>key;
return;
}
// get the number of the leaves recusively
unsigned int getLeafCount(BiNode* node)
{
if(node == NULL)
return 0;
if(node->LChild == NULL && node->RChild == NULL)
return 1;
return getLeafCount(node->LChild) + getLeafCount(node->RChild);
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化