代码是为了实现二叉树的横向显示问题。这种树形要求先打印右子树,再打印根,最后打印左子树,顺序恰为逆中序顺序。这种输出格式,结点的左右位置与结点的层深有关,故算法中设置了一个表示当前根节点层深的参数,以控制输出结点的左右位置。
示意图:
代码如下:
#include
<
stdio.h
>
#include < stdlib.h >
#define OVERFLOW -2
#define INFEASIBLE -1
#define ERROR 0
#define OK 1
#define TRUE 1
#define FALSE 0
typedef char TElemType;
TElemType Nil = ' # ' ;
typedef struct BiTNode
... {
TElemType data;
BiTNode *lchild,*rchild;
} BiTNode, * BiTree;
int InitBiTree(BiTree * T)
... {
*T=NULL;
return OK;
}
void CreateBiTree(BiTree * T)
... {
TElemType ch;
scanf("%c",&ch);
if(ch==Nil)
(*T)=NULL;
else
...{
(*T)=(BiTree)malloc(sizeof(BiTNode));
if(!(*T))
exit(OVERFLOW);
(*T)->data=ch;
CreateBiTree(&(*T)->lchild);
CreateBiTree(&(*T)->rchild);
}
}
void PrintTree(BiTree * T, int Layer)
... {/**//*按竖向树状打印的二叉树*/
int i;
if(*T==NULL)
return;
PrintTree(&(*T)->rchild,Layer+1);
for(i=0;i<Layer;i++)
printf(" ");
printf("%c ",(*T)->data); //按逆中序输出结点,用层深决定结点的左右位置
PrintTree(&(*T)->lchild,Layer+1);
}
void main()
... {
BiTNode* T;
InitBiTree(&T);
printf("请先序输入二叉树(如:AB###表示A为根结点,B为左子树的二叉树) ");
CreateBiTree(&T);
PrintTree(&T,0);
}
#include < stdlib.h >
#define OVERFLOW -2
#define INFEASIBLE -1
#define ERROR 0
#define OK 1
#define TRUE 1
#define FALSE 0
typedef char TElemType;
TElemType Nil = ' # ' ;
typedef struct BiTNode
... {
TElemType data;
BiTNode *lchild,*rchild;
} BiTNode, * BiTree;
int InitBiTree(BiTree * T)
... {
*T=NULL;
return OK;
}
void CreateBiTree(BiTree * T)
... {
TElemType ch;
scanf("%c",&ch);
if(ch==Nil)
(*T)=NULL;
else
...{
(*T)=(BiTree)malloc(sizeof(BiTNode));
if(!(*T))
exit(OVERFLOW);
(*T)->data=ch;
CreateBiTree(&(*T)->lchild);
CreateBiTree(&(*T)->rchild);
}
}
void PrintTree(BiTree * T, int Layer)
... {/**//*按竖向树状打印的二叉树*/
int i;
if(*T==NULL)
return;
PrintTree(&(*T)->rchild,Layer+1);
for(i=0;i<Layer;i++)
printf(" ");
printf("%c ",(*T)->data); //按逆中序输出结点,用层深决定结点的左右位置
PrintTree(&(*T)->lchild,Layer+1);
}
void main()
... {
BiTNode* T;
InitBiTree(&T);
printf("请先序输入二叉树(如:AB###表示A为根结点,B为左子树的二叉树) ");
CreateBiTree(&T);
PrintTree(&T,0);
}