DS二叉树--叶子数量

DS二叉树–叶子数量


题目描述

计算一颗二叉树包含的叶子结点数量。

提示:叶子是指它的左右孩子为空。

建树方法采用“先序遍历+空树用0表示”的方法,即给定一颗二叉树的先序遍历的结果为AB0C00D00,其中空节点用字符‘0’表示。则该树的逻辑结构如下图。

在这里插入图片描述


输入

第一行输入一个整数t,表示有t个测试数据

第二行起输入二叉树先序遍历的结果,空树用字符‘0’表示,输入t行


输出

逐行输出每个二叉树的包含的叶子数量


输入样例

3
AB0C00D00
AB00C00
ABC00D00E00


输出样例

2
2
3

代码

#include<iostream>
#include<string>
using namespace std;

class BiTreeNode {
public:
    char data;
    BiTreeNode *LeftChild;
    BiTreeNode *RightChild;
    BiTreeNode():LeftChild(NULL),RightChild(NULL) {}
    ~BiTreeNode(){}
};

class BiTree {
public:
    BiTree();
    void CreateBiTree(string s);
    void FindLeaves();
private:
    BiTreeNode * CreateBiTree();
    void FindLeaves(BiTreeNode *t);
    int pos;
    BiTreeNode *Root;
    string strTree;
};

int total = 0;

void BiTree::FindLeaves()
{
    FindLeaves(Root);
}

void BiTree::FindLeaves(BiTreeNode *t)
{
    if(t)
    {
        if(t->LeftChild)
            FindLeaves(t->LeftChild);
        if(t->RightChild)
            FindLeaves(t->RightChild);
        if(t->LeftChild==NULL&&t->RightChild==NULL)
            total++;
    }
}

BiTree::BiTree() {
    pos = 0;
    Root = NULL;
}

void BiTree::CreateBiTree(string s)
{
    strTree.assign(s);
    Root = CreateBiTree();
}

BiTreeNode *BiTree::CreateBiTree()
{
    BiTreeNode *T;
    char ch;
    ch = strTree[pos++];
    if(ch == '0')
        T = NULL;
    else
    {
        T = new BiTreeNode();
        T->LeftChild = CreateBiTree();
        T->RightChild = CreateBiTree();
    }
    return T;
}

int main()
{
    int n;
    cin>>n;
    for(int i=0;i<n;i++)
    {
        string s;
        cin>>s;
        BiTree biTree;
        biTree.CreateBiTree(s);
        biTree.FindLeaves();
        cout<<total<<endl;
        total = 0;
    }
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值