数据结构-二叉树的基本操作

#include <bits/stdc++.h>
using namespace std;

typedef struct btnode{
    char data;
    struct btnode *lchild,*rchild;
}btnode,*bitree;

bitree creat_btnode(string s,int &i,int len)
{// 利用先序遍历创建二叉树
// 参数:先序遍历字符串s,字符串初始下标i=0,字符串长度len。
// 返回:二叉树
    if(i>=len||s[i]=='#'){
        i++;
        return NULL;
    }
    bitree root =(bitree)malloc(sizeof(btnode));
    root->data=s[i];
    i++;
    root->lchild=creat_btnode(s, i, len);
    root->rchild=creat_btnode(s, i, len);
    return root;
}

void miorder(bitree root)
// 二叉树的中序遍历
{
    if(root!=NULL)
    {
        miorder(root->lchild);
        cout<<root->data;
        miorder(root->rchild);
    }
}

int deep_bitree(bitree root)
{// 计算该二叉树的深度
    int cnt=0;
    if(!root)
        return 0;
    cnt=1+max(deep_bitree(root->lchild),deep_bitree(root->rchild));
    return cnt;
}

int count_bitree(bitree root)
{// 计算该二叉树的总节点个数
    if(!root)
        return 0;
    return 1+count_bitree(root->lchild)+count_bitree(root->rchild);
}

int count_Leaf_bitree(bitree root)
{// 计算该二叉树的叶子节点个数
    if(!root)
        return 0;
    if(!root->lchild&&!root->rchild)
        return 1;
    return count_Leaf_bitree(root->lchild)+count_Leaf_bitree(root->rchild);
}

bitree bitreeshift(bitree root)
{
    // 递归实现二叉树左右子树的交换
    if(!root)
        return NULL;

    bitree temp=root->lchild;
    root->lchild=root->rchild;
    root->rchild=temp;

    if(root->lchild!=NULL){
        bitreeshift(root->lchild);
    }
    if(root->rchild!=NULL){
        bitreeshift(root->rchild);
    }
    return root;
}

int main()
{
    string s;
    cin>>s;
    int len=s.size();
    int i=0;
    bitree root=creat_btnode(s,i,len);
    miorder(root);
    cout<<endl;

    cout<<deep_bitree(root)<<endl;

    cout<<count_bitree(root)<<endl;

    cout<<count_Leaf_bitree(root)<<endl;
    return 0;
}
 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

可我不想做饼干

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

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

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

打赏作者

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

抵扣说明:

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

余额充值