DS二叉树--左叶子数量

找到子叶,然后返回真证明是子叶,只判断左孩子是不是子叶就ok

看点有趣的东西

 

 

 

#include <bits/stdc++.h>
using namespace std;
int num=0;
class BiTreeNode{
public:
    char date;
    BiTreeNode *leftchild;
    BiTreeNode *rightchild;
};
class BiTree{
private:
    BiTreeNode *Root; //根节点指针
    int pos;
    string strTree;
    BiTreeNode *CreateBirtree();
public:
    BiTree(){}
    ~BiTree(){}
    void CreateTree(string TreeArray);//利用先序遍历结果创建二叉树
    void PreOrder()//前序遍历
    {
        PreOrder(Root);
    }
    bool PreOrder(BiTreeNode *t);//用bool,只有当是子叶时返回真
};
//构造二叉树,利用先序遍历结果创建树
void BiTree::CreateTree(string TreeArray){
    pos=0;
    strTree.assign(TreeArray);
    Root=CreateBirtree();
}
BiTreeNode* BiTree::CreateBirtree() {
    BiTreeNode *T;
    char ch;
    ch = strTree[pos++];
    int flag = 0;
    if (ch == '0') return NULL;
    //如果没有返回的话,其实就会走下面的,相当于上面if的else
    //很奇怪。我宁愿写这么长的注释也不愿意写个else{}
    T = new BiTreeNode();
    T->date = ch;// 生成根节点
    T->leftchild = CreateBirtree();// 构造左子树
    T->rightchild = CreateBirtree();//构造右子树
    return T;
}
// 定义先序遍历函数
bool BiTree ::PreOrder(BiTreeNode *t) {//用bool,只有当是子叶时返回真
    if(t!=NULL){
        if(!t->leftchild&&!t->rightchild)
            return true;
        if(PreOrder(t->leftchild))//只判断左子叶
            num++;
        //3.visit the  rightchild;
        PreOrder(t->rightchild);
    }
    return false;
}


int main()
{
    int t;cin>>t;
    for (int i = 0; i < t; ++i) {
        num=0;
        string str; cin>>str;
        BiTree *tree;
        tree=new BiTree();
        tree->CreateTree(str);
        tree->PreOrder();
        cout<<num<<endl;
    }
}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值