代码拉取完成,页面将自动刷新
#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);
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。