利用先序递归遍历算法创建二叉树并输出该二叉树中指定结点的度。约定二叉树结点数据为单个大写英文字符。当接收的数据是字符“#”时表示该结点不需要创建,否则创建该结点。最后再输出创建完成的二叉树中的指定结点的度。注意输入数据序列中的字符“#”和非“#”字符的序列及个数关系,这会最终决定创建的二叉树的形态。
输入
输入用例分2行输入,第一行接受键盘输入的由大写英文字符和“#”字符构成的一个字符串(用于创建对应的二叉树),第二行为指定的结点数据。
输出
用一行输出该用例对应的二叉树中指定结点的度。
样例输入
A##
A
ABC####
B
样例输出
0
1
#include <iostream> #include <stdlib.h> using namespace std; typedef struct tree { char date; tree *left,*right; }Tree; void creat(Tree*&T)//先序遍历创建二叉树 { char str; cin>>str; if(str!='#') { T = (Tree*)malloc(sizeof(Tree)); T->date = str; creat(T->left); creat(T->right); } else { T=NULL; } } void find(Tree *&T,char elem) { if(elem ==T->date) { int i=0; if(T->left!=NULL) { i++; } if(T->right!=NULL) { i++; } cout<<i; } if(T->left!=NULL) { find(T->left,elem); } if(T->right!=NULL) { find(T->right,elem); } } int main() { Tree *T; creat(T); char elem; cin>>elem; find(T,elem); return 0; }