二叉树模板

根据先序遍历建树

const int N=2e6+10;
struct node
{
    char date;
    int l,r;
}str[N];
string s; //读入先序遍历
int cnt,idx;
int build()
{
    if (s[cnt]=='#')
    {
        cnt++;
        return 0;
    }
    str[++idx].date=s[cnt++];
    int now=idx;
    str[now].l=build();
    str[now].r=build();
    return now;
}

int u=build();//返回根节点

根据先序和中序建树

const int N=2e6+10;
struct node
{
    int date;
    int l,r;
}str[N];
int pre[N],mid[N],n;//读入先序顺序和中序顺序
int cnt,idx;
int build(int len,int pre[],int mid[])
{
    if (len<=0) return 0;
    str[++idx].date=pre[0];
    int i;
    for (i=0;i<len;i++)
    {
        if (mid[i]==pre[0]) break;
    }
    int now=idx;
    str[now].l=build(i,pre+1,mid);
    str[now].r=build(len-i-1,pre+i+1,mid+i+1);
    return now;
}

int u=build(n,pre,mid);//返回根节点

根据中序和后序建树

const int N=2e6+10;
struct node
{
    int date;
    int l,r;
}str[N];
int mid[N],post[N],n;//读入中序顺序和后序顺序
int cnt,idx;
int build(int len,int mid[],int post[])
{
    if (len<=0) return 0;
    str[++idx].date=post[len-1];
    int i;
    for (i=0;i<len;i++)
    {
        if (mid[i]==post[len-1]) break;
    }
    int now=idx;
    str[now].l=build(i,mid,post);
    str[now].r=build(len-i-1,mid+i+1,post+i);
    return now;
}

int u=build(n,mid,post);//返回根节点

四种遍历

1.先序遍历

void Pre(int u)
{
    if (!u) return ;
    cout<<str[u].date;
    Pre(str[u].l);
    Pre(str[u].r);
}

2.中序遍历

void Mid(int u)
{
    if (!u) return ;
    Mid(str[u].l);
    cout<<str[u].date;
    Mid(str[u].r);
}

3.后序遍历

void Post(int u)
{
    if (!u) return ;
    Post(str[u].l);
    Post(str[u].r);
    cout<<str[u].date;
}

4.层序遍历

void bfs(int u)
{
    queue <int> q;
    q.push(u);
    while (q.size())
    {
        int t=q.front();
        q.pop();
        cout<<str[t].date;
        if (str[t].l) q.push(str[t].l);
        if (str[t].r) q.push(str[t].r);
    }
}

树的高度

int deep(int u)
{
    if (!u) return 0;
    return max(deep(str[u].l),deep(str[u].r))+1;
}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值