【数据结构OJ】C : DS二叉树--左叶子数量

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;
}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值