数据结构与算法作业题,如有不正确或者需要改进的地方请指正,谢谢。
其中是使用了扩展二叉树方法创建二叉树的函数,以及先根遍历二叉树,最后是求得度为2的结点的函数NodeCount2()。
#include<iostream>
using namespace std;
typedef struct lrpNode
{
char data;
lrpNode* lc, * rc;
lrpNode() :data(' '), lc(NULL), rc(NULL) {}
}*lrpTree;
lrpTree create_lrpTree(string str, int& idx)//扩展二叉树
{
lrpTree ret;
if (str[idx] == '#' || idx == str.size())
{
idx++;
return NULL;
}
ret = new lrpNode;
ret->data = str[idx++];
ret->lc = create_lrpTree(str, idx);
ret->rc = create_lrpTree(str, idx);
return ret;
}
void print_lrpTree(lrpTree rt)
{
if (rt == NULL)return;
cout << rt->data << " ";
if (rt->lc && rt->lc->data != '#')
cout << "lc:" << rt->lc->data << " ";
else cout << "lc:NULL" << " ";
if (rt->rc && rt->rc->data != '#')
cout << "rc:" << rt->rc->data << " ";
else cout << "rc:NULL" << " " << endl;
print_lrpTree(rt->lc);
print_lrpTree(rt->rc);
}
int NodeCount2(lrpTree rt)
{
if (!rt) return 0;
int cn = 0;
if (rt->lc != NULL && rt->rc != NULL) cn++;
cn += NodeCount2(rt->lc);
cn += NodeCount2(rt->rc);
return cn;
}
int main()
{
string str = "ABD##EG###CF#H###";
int idx = 0;
lrpTree rt = create_lrpTree(str, idx);
print_lrpTree(rt);
cout << "度为2的节点的个数为:" << NodeCount2(rt);
delete rt;
}