穿线二叉树(注释了一些有用的解释)

来源:互联网 发布:mac如何登陆apple id 编辑:程序博客网 时间:2024/04/30 08:27

typedef char datatype;
typedef struct node{
   datatype data;
   struct node *lchild,*rchild;
}bintnode;
typedef bintnode *binthrtree;
binthrtree root;

binthrtree pre=NULL;
void createbintree(binthrtree *t)
{char ch;
 if((ch=getchar())==' ')
    *t=NULL;
 else{
     *t=(binthrnode *)malloc(sizeof(binthrnode));
     (*t)->data=ch;
     createbintree(&(*t)->lchild));   //引用传递,要看清
     createbintree(&(*t)->rchild));
 }
}
void inthreading(binthrtree *p)
{if(*p)
 {inthreading(&((*p)->lchild));    //按照中序遍历先对左子树穿线遍历
  (*p)->ltag=((*p)->lchild)?0:1;   
  (*p)->rtag=((*p)->rchild)?0:1;
  if(pre)                                          //如果前序结点存在
  {if(pre->rtag==1)  pre->rchild=*p;
   if((*p)->ltag==1) (*p)->lchild=pre;
  }
  pre=*p;                                    //中序向前遍历下一个结点(链式存储)
  inthreading(&((*p)->rchild));
 }
}
void createthrtree(binthrtree *p)
{createbintree(p);
 inthreading(p);
}

原创粉丝点击