Description
计算一颗二叉树包含的叶子结点数量。
左叶子是指它的左右孩子为空,而且它是父亲的左孩子
提示:可以用三叉链表法,也可以用现有算法对两层结点进行判断
建树方法采用“先序遍历+空树用0表示”的方法
Input
第一行输入一个整数t,表示有t个测试数据
第二行起输入二叉树先序遍历的结果,空树用字符‘0’表示,输入t行
Output
逐行输出每个二叉树的包含的左叶子数量
Sample
samplein
3
AB0C00D00
AB00C00
ABCD0000EF000
sampleout
0
1
2
AC代码
#include <iostream>
#include <string>
using namespace std;
class BitNode {
public:
char data;
BitNode* lchild;
BitNode* rchild;
BitNode* parent;
};
class Bitree {
public:
BitNode* root;
int flag;
Bitree(const string& str) {
flag = 0;
int pos = 0;
root = createTree(str, pos);
}
BitNode* createTree(const string& str, int& pos) {
if (pos >= str.length()) {
return nullptr;
}
char ch = str[pos++];
if (ch == '0') {
return nullptr;
}
else {
BitNode* b = new BitNode();
b->data = ch;
b->lchild = createTree(str, pos);
if (b->lchild != nullptr) {
b->lchild->parent = b;
}
b->rchild = createTree(str, pos);
if (b->rchild != nullptr) {
b->rchild->parent = b;
}
return b;
}
}
void getLchildLeaf(BitNode* b) {
if (b != nullptr && b->parent != nullptr && b->parent->lchild == b) {
if (b->lchild == nullptr && b->rchild == nullptr) {
flag++;
}
}
if (b->lchild != nullptr) {
getLchildLeaf(b->lchild);
}
if (b->rchild != nullptr) {
getLchildLeaf(b->rchild);
}
}
};
int main() {
int t;
cin >> t;
while (t--) {
string str;
cin >> str;
Bitree b(str);
b.getLchildLeaf(b.root);
cout << b.flag << endl;
}
return 0;
}