目录
题目
题目描述
利用先序递归遍历算法创建二叉树并输出该二叉树中指定结点的度。约定二叉树结点数据为单个大写英文字符。当接收的数据是字符“#”时表示该结点不需要创建,否则创建该结点。最后再输出创建完成的二叉树中的指定结点的度。注意输入数据序列中的字符“#”和非“#”字符的序列及个数关系,这会最终决定创建的二叉树的形态。
输入
输入用例分2行输入,第一行接受键盘输入的由大写英文字符和“#”字符构成的一个字符串(用于创建对应的二叉树),第二行为指定的结点数据。
输出
用一行输出该用例对应的二叉树中指定结点的度。
样例输入
A## A ABC#### B样例输出
0
思路
先序遍历找到指定的节点即可,然后看左右孩子有几个为空,若都是空,则度为0,若一个为空,则度为1,若都不为空,则度为2。
void BTSearch(BinaryTree* &root,char key) {
if(root==NULL) return;
if(root->data==key) {
if(root->left==NULL && root->right==NULL) {
cout<<0;
exit(0);
}
else if(root->left==NULL && root->right!=NULL) {
cout<<1;
exit(0);
}
else if(root->right==NULL && root->left!=NULL) {
cout<<1;
exit(0);
}
else {
cout<<2;
exit(0);
}
}
BTSearch(root->left,key);
BTSearch(root->right,key);
return;
}
代码
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cmath>
typedef long long ll;
using namespace std;
//定义二叉树
typedef struct BTNode {
char data;
BTNode* left;
BTNode* right;
}BinaryTree;
//创建二叉树
void BTCreate(BinaryTree* &root) {
BTNode* q;
q=new BTNode;
cin>>q->data;
if(q->data=='#') {
root=q=NULL;
return;
}
root=q;
BTCreate(root->left);
BTCreate(root->right);
}
void BTSearch(BinaryTree* &root,char key) {
if(root==NULL) return;
if(root->data==key) {
if(root->left==NULL && root->right==NULL) {
cout<<0;
exit(0);
}
else if(root->left==NULL && root->right!=NULL) {
cout<<1;
exit(0);
}
else if(root->right==NULL && root->left!=NULL) {
cout<<1;
exit(0);
}
else {
cout<<2;
exit(0);
}
}
BTSearch(root->left,key);
BTSearch(root->right,key);
return;
}
int main() {
BinaryTree *root;
BTCreate(root);
char key;cin>>key;
BTSearch(root,key);
return 0;
}