二叉树模板

根据先序遍历建树

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

根据中序和后序建树

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

四种遍历

1.先序遍历

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

2.中序遍历

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

3.后序遍历

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

4.层序遍历

void bfs(int u)
{
    queue  q;
    q.push(u);
    while (q.size())
    {
        int t=q.front();
        q.pop();
        cout<

树的高度

int deep(int u)
{
    if (!u) return 0;
    return max(deep(str[u].l),deep(str[u].r))+1;
}

你可能感兴趣的:(算法,数据结构)