找到子叶,然后返回真证明是子叶,只判断左孩子是不是子叶就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;
}
}