二叉树——魔板

版权声明:叁土 https://blog.csdn.net/qq_42847312/article/details/81630539

二叉树结构:


typedef struct tree
{
    cahr data;
    struct tree *l,*r;
} tr;

建立二叉树 / 创立结点:


tr *creat(tr *root)//看具体情况
{
    if(a[i++]==',')  root=NULL;
    else
    {
        root=(tr *)malloc(sizeof(tr));
        root->data=a[i];
        root->l=creat(root->l);
        root->r=creat(root->r);
    }
    return root;
}

先序遍历:根—>左子树—>右子树


void xi(tr *root)
{
    if(root)
    {
        printf("%c",root->data);
        xi(root->l);
        xi(root->r);
    }
}

中序遍历:左子树—>根—>右子树


void zh(tr *root)
{
    if(root)
    {
        zh(root->l);
        printf("%c",root->data);
        zh(root->r);
    }
}

后序遍历:左子树—>右子树—>根


void ho(tr *root)
{
    if(root)
    {
        ho(root->l);
        ho(root->r);
        printf("%c",root->data);
    }
}

层次遍历:从上到下,从左到右,逐层遍历


void ch(struct node *root)
{
    struct node *t[100];
    int in=0,out=0;
    t[in++]=root;
    while(in>out)
    {
        if(t[out])
        {
            printf("%c",t[out]->data);
            t[in++]=t[out]->l;
            t[in++]=t[out]->r;
        }
        out++;
    }
}

二叉树的深度:


int deep(struct node *root)
{
    if(root)
    {
        int q=deep(root->l)+1;
        int w=deep(root->r)+1;
        return q>w?q:w;
    }
    else return 0;
}

二叉树叶子个数:


int yezis(tr *root)
{
    int K(struct node *root)
    {
        if(root==NULL) return 0;
        if(root->l==NULL&&root->r==NULL) return 1;
        else return yezis(root->l)+yezis(root->r);
    }
}

二叉树叶子结点:


void yezij(struct node *root)
{
    queue<node*>q;
    q.push(root);
    tr *t;
    while(!q.empty())
    {
        t=q.front();
        q.pop();
        if(t)
        {
            if(t->l==NULL&&t->r==NULL)
                cout<<t->data;
            q.push(t->l);
            q.push(t->r);
        }
    }
}

已知先序+中序—>后序:


struct node *creat(int n,char *str1,char *str2)//  n=strlen(str1),二叉树的先序遍历的第一个节点是子树的根,中序遍历中根节点的左边全都是左子树的中序,右边是右子树的中序
{
    struct node *root;
    char *p;
    if(n==0)//当节点为零时表明数据全部进入二叉树;
        return NULL;
    root=(struct node *)malloc (sizeof(struct node));
    root->data=str1[0];//先序的第一个为根节点
    for(p=str2; p!='\0'; p++)
    {
        if(*p==str1[0])//在中序中找到根节点,从而分为左右两个部分;
            break;
    }
    int t=p-str2;//左子树节点的个数
    root->l=creat(t,str1+1,str2);//递归创建左子树;
    root->r=creat(n-t-1,str1+t+1,p+1);//递归创建右子树
    return root;
};

余生还请多多指教!

猜你喜欢

转载自blog.csdn.net/qq_42847312/article/details/81630539