# 基础数据结构-二叉树-拓展：计算二叉树的左叶子数

3
AB0C00D00
AB00C00
ABCD0000EF000

0
1
2

```#include<iostream>
#include<string>
using namespace std;
int sum=0;
class BiTreeNode{
public:
char data;
BiTreeNode *LeftChild;
BiTreeNode *RightChild;
BiTreeNode():LeftChild(NULL),RightChild(NULL){}
~BiTreeNode(){}
};

class BiTree{
private:
BiTreeNode *Root;
int pos;
string strTree;
BiTreeNode* CreateBiTree();
void PreOrder(BiTreeNode* t);
void InOrder(BiTreeNode* t);
void PostOrder(BiTreeNode* t);
public:
BiTree(){};
~BiTree(){};
void CreateTree(string TreeArray);
void PreOrder();
void InOrder();
void PostOrder();
};

void BiTree::CreateTree(string TreeArray)
{
pos=0;
strTree.assign(TreeArray);
Root=CreateBiTree();
}

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

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

void BiTree::PreOrder(BiTreeNode* t)
{
if(t)
{
if(t->LeftChild){
PreOrder(t->LeftChild);
}
else if(!t->RightChild)  sum++;
if(t->RightChild&&t->RightChild->LeftChild) PreOrder(t->RightChild->LeftChild);
}
}

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

void BiTree::InOrder(BiTreeNode* t)
{
if(t)
{
InOrder(t->LeftChild);
cout<<t->data;
InOrder(t->RightChild);
}
}

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

void BiTree::PostOrder(BiTreeNode*t)
{
if(t)
{
PostOrder(t->LeftChild);
PostOrder(t->RightChild);
cout<<t->data;
}
}

int main()
{
int t;
string str;
BiTree BT;
BiTreeNode BTN;
cin>>t;
while(t--)
{
sum=0;
cin>>str;
BT.CreateTree(str);
BT.PreOrder();
cout<<sum<<endl;
}
return 0;
}```

原文作者：Nathaneko
原文地址: https://www.cnblogs.com/nathaneko/p/6491898.html
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。