天天看點

二叉樹前序、中序、後序周遊

根據網絡代碼優化,可以運作:(有空再追加注釋)

#include<stdio.h>

#include<stdlib.h>

typedef char TypeData;

typedef struct stBiTreeNode

{

TypeData data;

struct stBiTreeNode *lchild;

struct stBiTreeNode *rchild;

}BITREENODE;

BITREENODE* createBiTree()

{

char chTempData = 0;

BITREENODE *pstNewNode = NULL;

scanf("%c", &chTempData);

if(chTempData == '#')

{

pstNewNode = NULL;

}

else

{

pstNewNode = (BITREENODE*)malloc(sizeof(BITREENODE)+1);

pstNewNode->data = chTempData;

pstNewNode->lchild = createBiTree();

pstNewNode->rchild = createBiTree();

}

return pstNewNode;

}

int preVisitBiTree(BITREENODE* InRoot)

{

if(InRoot)

{

printf("%c ", InRoot->data);

preVisitBiTree(InRoot->lchild);

preVisitBiTree(InRoot->rchild);

}

return 0;

}

int inVisitBiTree(BITREENODE* InRoot)

{

if(InRoot)

{

inVisitBiTree(InRoot->lchild);

printf("%c ", InRoot->data);

inVisitBiTree(InRoot->rchild);

}

return 0;

}

int postVisitBiTree(BITREENODE* InRoot)

{

if(InRoot)

{

postVisitBiTree(InRoot->lchild);

postVisitBiTree(InRoot->rchild);

printf("%c ", InRoot->data);

}

return 0;

}

int main()

{

BITREENODE* pstRoot;

pstRoot = createBiTree();

preVisitBiTree(pstRoot);

printf("\n");

inVisitBiTree(pstRoot);

printf("\n");

postVisitBiTree(pstRoot);

return 0;

}

輸入:ABH##FD###E#CK##G##

輸出:A B H F D E C K G 

   H B D F A E K C G 

   H D F B K G C E A

繼續閱讀