用户注册



邮箱:

密码:

用户登录


邮箱:

密码:
记住登录一个月忘记密码?

发表随想


还能输入:200字
云代码 - c代码库

二叉树的线性化

2013-03-08 作者: 神马举报

[c]代码库

#include<stdio.h>
#include<stdlib.h>
struct node {
    int data;
    struct node *lh,*rh;
    int ltag,rtag;
}*pr,*t,*s[30];
 
struct node* creat() {
    struct node *t,*q;
    int i,x,j;
    printf ( "i,x=" );
    scanf ( "%d%d",&i,&x );
    while ( ( i!=0 ) && ( x!=0 ) ) {
        q= ( struct node * ) malloc ( sizeof ( struct node ) );
        q->data=x;
        q->lh=NULL;
        q->rh=NULL;
        s[i ]=q;
        if ( i==1 )
            t=q;
        else {
            j=i/2;
            if ( ( i%2 ) ==0 )
                s[j]->lh=q;
            else
                s[j]->rh=q;
        }
        printf ( "i,x=" );
        scanf ( "%d%d",&i,&x );
    }
    return ( t );
}
 
/*void inthread(struct node *p) //递归算法
{
    if(p!=NULL)
    {
        inthread(p->lh);
        printf("%6d\t",p->data);
        if(p->lh!=NULL)
            p->ltag=0;
        else
        {
            p->ltag=1;
            p->lh=pr;
        } //建立P节点的左线索,指向前趋节点PR
        if(pr!=NULL)
        {
            if(pr->rh!=NULL)
                pr->rtag=0;
            else
            {
                pr->rtag=1;
                pr->rh=p;
            }//前趋节点PR建立左线索,指向节点P
        }
        pr=p;//pr跟上p,以便p向后移动
        inthread(p->rh);
    }
}*/
 
void inthread ( struct node *t ) { //非递归算法
    int top,bools;
    struct node *p;
    pr=NULL;
    p=t;
    top=0;
    bools=1;
    do {
        while ( p!=NULL ) {
            top++;
            s[top]=p;
            p=p->lh;
        }
        if ( top==0 ) bools=0;
        else {
            p=s[top];
            top--;
            printf ( "%6d",p->data );
            if ( p->lh!=NULL )
                p->ltag=0;
            else {
                p->ltag=1;
                p->lh=pr;
            } //建立P节点的左线索,指向前趋节点PR
            if ( pr!=NULL ) {
                if ( pr->rh!=NULL )
                    pr->rtag=0;
                else {
                    pr->rtag=1;
                    pr->rh=p;
                }//前趋节点PR建立左线索,指向节点P
            }
            pr=p;//pr跟上p,以便p向后移动
            p=p->rh;
        }//END else
    } while ( bools );
    pr->rh=NULL;
}
 
main() {
    pr=NULL;
    t=creat();
    inthread ( t );
    pr->rh=NULL;
}


网友评论    (发表评论)


发表评论:

评论须知:

  • 1、评论每次加2分,每天上限为30;
  • 2、请文明用语,共同创建干净的技术交流环境;
  • 3、若被发现提交非法信息,评论将会被删除,并且给予扣分处理,严重者给予封号处理;
  • 4、请勿发布广告信息或其他无关评论,否则将会删除评论并扣分,严重者给予封号处理。


扫码下载

加载中,请稍后...

输入口令后可复制整站源码

加载中,请稍后...