中序遍歷訣竅 用C語言編程實(shí)現(xiàn)二叉樹的中序遍歷算法?
用C語言編程實(shí)現(xiàn)二叉樹的中序遍歷算法?#Include#Includestruct bitnode*stack[100]struct bitnode//define struct{char datas
用C語言編程實(shí)現(xiàn)二叉樹的中序遍歷算法?
#Include
#Include
struct bitnode*stack[100
]struct bitnode//define struct
{
char data
struct bitnode*lchild,*rchild
}
void later(struct bitnode*&)//preorder create tree
{
char Ch
scanf scanf(%C”,&;Ch)
if(Ch=”)
P=null
else{
P=(struct bitnode*)malloc(sizeof(struct bitnode*)bitnode)
P->data=ch
以后(P->lchild)
以后(P->rchild)
}
void print(struct bitnode*P)//前序遍歷(輸出二叉樹)
{
int i=-1
while(1)
{
while P!=null)
]{
堆棧[i]=P->rchild/*printf(”確定?N“)*/
printf(”%C“,P->data)
P=P->lchild
}]如果(I!=-1)
{
P=stack[i
]i-->]else
return
}
void main()//主函數(shù)
{
]struct bitnode*P,*t
稍后(P)
print(P)
}
知樹的前序遍歷,后序遍歷,怎么求中序遍歷?
首先了解概念:前序遍歷:訪問根節(jié)點(diǎn)的操作發(fā)生在遍歷其左右子樹之前。中間順序遍歷:訪問根節(jié)點(diǎn)的操作發(fā)生在遍歷其左右子樹時(shí)。后序遍歷:訪問根節(jié)點(diǎn)的操作發(fā)生在遍歷其左右子樹之后。例:遍歷dbcefgha后,為了遍歷edcbahfg,先查找前序遍歷(聯(lián)機(jī)示例)解決方案:遍歷dbcefgha后,先看a是總根節(jié)點(diǎn),然后按順序遍歷edcbahfg找到a的位置,然后edcb在a的左分支,HFG在a的右分支。重復(fù)前兩步,查找從最后一個(gè)位置對應(yīng)點(diǎn)進(jìn)行遍歷后,依次找到左右分支進(jìn)行遍歷,最后得到aecdbhgf,然后自己驗(yàn)證