SWUST OJ#1053 输出利用先序遍历创建的二叉树中的指定结点的度

目录

题目

思路

代码


题目

题目描述

利用先序递归遍历算法创建二叉树并输出该二叉树中指定结点的度。约定二叉树结点数据为单个大写英文字符。当接收的数据是字符“#”时表示该结点不需要创建,否则创建该结点。最后再输出创建完成的二叉树中的指定结点的度。注意输入数据序列中的字符“#”和非“#”字符的序列及个数关系,这会最终决定创建的二叉树的形态。

输入

输入用例分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;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

是孤衾呀

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值