AB - 二叉树的三种建树方法,四种遍历方法

根据已知先序遍历建立二叉树(带空结点)


Tree* buildtree_pre()
{
    if(pre[cnt]==',')
    {
        cnt++;
        return NULL;
    }

    Tree *root = new Tree;
    root->data=pre[cnt++];
    root->l=buildtree_pre();
    root->r=buildtree_pre();
    return root;
}

根据先序遍历和中序遍历建立二叉树


Tree* buildtree_pre_mid(int len,char pre[],char mid[])
{
    if(!len)
        return NULL;
    Tree *root = new Tree;
    root->data=pre[0];
    int i;
    for(i=0;i<len;i++)
    {
        if(mid[i]==pre[0])
            break;
    }
    root->l=buildtree_pre_mid(i,pre+1,mid);
    //左子树起点
    root->r=buildtree_pre_mid(len-i-1,pre+i+1,mid+i+1);
    //len-i-1:总长度-左子树-根,是右子树的起点
    //pre+i+1:先序遍历中左子树起点
    //mid+i+1:中序遍历中右子树起点
    return root;
}

根据中序遍历和后序遍历建立二叉树


Tree* buildtree_mid_post(int len,char mid[],char post[])
{
    if(!len)
        return NULL;
    Tree *root = new Tree;
    root->data=post[len-1];
    int i;
    for(i=0;i<len;i++)
    {
        if(mid[i]==post[len-1])
            break;
    }
    root->l=buildtree_mid_post(i,mid,post);
    //左子树起点
    root->r=buildtree_mid_post(len-i-1,mid+i+1,post+i);
    //mid+i+1:中序遍历中右子树起点
    //post+i:后序遍历中右子树起点
    return root;
}

先序、中序、后序遍历


//先序遍历
void pre_Travel(Tree *root)
{
    if(root)
    {
        cout<<root->data;
        pre_Travel(root->l);
        pre_Travel(root->r);
    }
}

//中序遍历
void mid_Travel(Tree *root)
{
    if(root)
    {
        mid_Travel(root->l);
        cout<<root->data;
        mid_Travel(root->r);
    }
}

//后序遍历
void post_Travel(Tree *root)
{
    if(root)
    {
        post_Travel(root->l);
        post_Travel(root->r);
        cout<<root->data;
    }
}

层序遍历


void Sequence_Travel(Tree *root)
{
    queue<Tree *> t;
    //使用队列实现
    t.push(root);
    //根入队
    while(!t.empty())
    {
        root=t.front();
        t.pop();
        //取队头并删除
        if(root)
        {
            cout<<root->data;
            t.push(root->l);
            t.push(root->r);
            //递归
        }
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值