二叉树的部分基础操作

#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
typedef struct node tree;
struct node
{
    char data;
    struct node *left;
    struct node *right;
};
tree *root;
char ch;
string str;
int i=0;
tree *CreateBinTree()
{
    tree *p;
    if(str[i++]==',')
        p=NULL;
    else
    {
        p=new tree;
        p->data=str[i-1];
        p->left=CreateBinTree();
        p->right=CreateBinTree();
    }
    return p;
}
void mid_order(tree *root)
{
    if(root)
    {
        mid_order(root->left);
        cout<<root->data;
        mid_order(root->right);
    }
}
void post_order(tree *root)
{
    if(root)
    {
        post_order(root->left);
        post_order(root->right);
        cout<<root->data;
    }
}
int yenum(tree *root)
{
    if(root==NULL)
        return 0;
    else if(root->left==NULL&&root->right==NULL)
        return 1;
    else
        return yenum(root->left)+yenum(root->right);
}
int shendu(tree *root)
{
    if(!root)
        return 0;
    else
        return max(1+shendu(root->left),1+shendu(root->right));

}
queue<tree*>que;
void cengxu(tree *root)
{
    tree *p;
    if(root==NULL) return;
    que.push(root);
    while(!que.empty())
    {
        p=que.front();
        que.pop();
        //if(p->left==NULL&&p->right==NULL)//用于只输出叶节点
            cout<<p->data;
        if(p->left) que.push(p->left);
        if(p->right) que.push(p->right);
    }

}
tree *huanyuan(int n,char a[],char b[])
{
    tree *p;
    p=new tree;
    if(n==0)
        p=NULL;
    else
    {
        int i;
        for(i=0;i<n;++i)
        {
            if(a[0]==b[i])
            {
                break;
            }
        }
        p->data=b[i];
        p->left=huanyuan(i,a+1,b);
        p->right=huanyuan(n-i-1,a+i+1,b+i+1);
    }
    return p;
}
void pre_order(tree *root)
{
    if(root)
    {
        cout<<root->data;
        pre_order(root->left);
        pre_order(root->right);
    }
}
int main()
{
    char a[55],b[55];
    int n,t;
    cin>>t;
    while(t--)
    {
        cin>>a>>b;
        n=strlen(a);
        root=NULL;
        root=huanyuan(n,a,b);
        root=CreateBinTree();
        pre_order(root);
        cout<<endl;
        mid_order(root);
        cout<<endl;
        post_order(root);
        cout<<endl;
        cout<<yenum(root)<<endl;
        cout<<shendu(root)<<endl;
        cengxu(root);
        cout<<endl;
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值