题目描述
利用先序递归遍历算法创建二叉树并计算该二叉树中的空链域个数。
输入
输入为接受键盘输入的由大写英文字符和"#"字符构成的一个字符串(用于创建对应的二叉树)。
输出
输出该用例对应的二叉树中的空链域个数。
样例输入复制
AB##C## ABCD###EF##G###
样例输出复制
4 8
要点:二叉树中空链域个数
对一个二叉树来说,含有n个结点的二叉链表中有n+1个空链域
每一个节点有左右两个指针,n个节点共有2n个链域,
而n个节点只需用n-1个指针就可互连(因为连接n个点只需n-1条直线),
所以还剩下2n-(n-1)=n+1个
所以只需要遍历计算出二叉树的结点数再+1即可
void Area(Tree *&tree) { if(tree!=NULL) { count++; if(tree->lchild!=NULL) Area(tree->lchild); if(tree->rchild!=NULL) Area(tree->rchild); } }
或者
void CreateTree(Tree *&t) { char army; cin>>army; if(army=='#') { t=NULL; } else { k++;//直接统计输入的不为NULL的结点数 t=new Tree; t->bts=army; CreateTree(t->lchild); CreateTree(t->rchild); } }
完整代码:
#include<iostream> #include<malloc.h> int count=0; using namespace std; typedef struct node { char data; struct node *lchild,*rchild; }Tree; void CreateTree(Tree *&tree) { char ch; cin>>ch; if(ch=='#') tree=NULL; else { tree=(Tree*)malloc(sizeof(Tree)); tree->data=ch; CreateTree(tree->lchild); CreateTree(tree->rchild); } } void Area(Tree *&tree) { if(tree!=NULL) { count++; if(tree->lchild!=NULL) Area(tree->lchild); if(tree->rchild!=NULL) Area(tree->rchild); } } int main() { Tree *tree; CreateTree(tree); Area(tree); cout<<count+1; return 0; }
浙公网安备 33010602011771号