编程求以孩子兄弟表示法存储的森林的叶节点数
#include <iostream>
typedef struct node{
char data;
struct node * pchild;
struct node * pbrother;
}node,*pnode;
pnode buynode(char x)
{
node* tmp=(pnode) malloc(sizeof (node));
tmp->data=x,tmp->pchild= nullptr,tmp->pbrother= nullptr;
return tmp;
}
//图为p190页t2的树
pnode build_tree()
{
pnode root= buynode('A');
root->pchild= buynode('B');
root->pchild->pbrother= buynode('C');
root->pbrother= buynode('D');
root->pbrother->pchild= buynode('E');
root->pbrother->pchild->pchild= buynode('F');
root->pbrother->pbrother= buynode('G');
root->pbrother->pbrother->pchild= buynode('H');
root->pbrother->pbrother->pchild->pbrother= buynode('I');
root->pbrother->pbrother->pchild->pbrother->pbrother= buynode('J');
root->pbrother->pbrother->pchild->pbrother->pbrother->pchild= buynode('M');
root->pbrother->pbrother->pchild->pbrother->pbrother->pchild->pchild= buynode('P');
root->pbrother->pbrother->pchild->pbrother->pbrother->pchild->pbrother= buynode('N');
root->pbrother->pbrother->pchild->pbrother->pbrother->pchild->pbrother->pbrother= buynode('O');
root->pbrother->pbrother->pchild->pchild= buynode('K');
root->pbrother->pbrother->pchild->pchild->pbrother= buynode('L');
return root;
}
int leaves(pnode root)
{
if(root== nullptr) return 0;
if(root->pchild== nullptr) {
printf("%3c", root->data);
return 1 + leaves(root->pbrother);
}
else return leaves(root->pchild)+leaves(root->pbrother);
}
int main() {
pnode root=build_tree();
printf("the leaves are:");
printf("%3d\n", leaves(root));
return 0;
}