题目描述
计算一颗二叉树包含的叶子结点数量。
左叶子是指它的左右孩子为空,而且它是父亲的左孩子
提示:可以用三叉链表法,也可以用现有算法对两层结点进行判断
建树方法采用“先序遍历+空树用0表示”的方法
输入
第一行输入一个整数t,表示有t个测试数据
第二行起输入二叉树先序遍历的结果,空树用字符‘0’表示,输入t行
输出
逐行输出每个二叉树的包含的左叶子数量
样例查看模式
正常显示
查看格式
输入样例1 <-复制
3
AB0C00D00
AB00C00
ABCD0000EF000
输出样例1
0
1
2
#include <iostream>
using namespace std;
class node{
public:
char val;
node *left,*right;
node(){
val='0';left= nullptr;right= nullptr;
}
};
node *root;
node* create(node *&p){
p=new node();
cin>>p->val;
if(p->val!='0'){
p->left= create(p->left);
p->right= create(p->right);
}
return p;
}
void pre(node *p){
if(p->left&&p->left->val=='0')p->left= nullptr;
if(p->right&&p->right->val=='0')p->right= nullptr;
if(p->left)pre(p->left);
if(p->right)pre(p->right);
}int f=0;
void js(node*p){
if(p->left&&!p->left->left&!p->left->right)f++;
if(p->left)js(p->left);
if(p->right)js(p->right);
}
int main(){
int t;cin>>t;
while (t--){
create(root);
pre(root);
f=0;
js(root);cout<<f<<endl;
}
}