二叉樹的建立和遍歷

2021-07-06 06:03:33 字數 1731 閱讀 3489

#include#include #define max_len 50

#define elemtype char

#define status int

#define ok 1

#define error 0

#define overflow -1

typedef struct nodebitreenode,*bitree;

/*遞迴建立一棵二叉樹*/

void createbitreebyrec(bitree &t)else

t->data = ch;

createbitreebyrec(t->lchild);

createbitreebyrec(t->rchild); }}

/*前序非遞迴建立二叉樹*/

void createbitreebyprenorec(bitree &t),p=null;

int top = 0;//棧頂指標

scanf("%c",&ch);

if('#'==ch)else

t->data = ch;

s[++top] = t;

p = t;

} while(top!=0)

if(ch!='#')

r->data = ch;

r->lchild = null;

r->rchild = null;

p->lchild = r;

p = r;

s[++top] = r;

}else

if(top!=0)

r->data = ch;

r->lchild = null;

r->rchild = null;

p->rchild = r;

p = r;

s[++top] = r;

}} }

}/*前序遞迴遍歷*/

void preorderrec(bitree &t)

}/*前序非遞迴遍歷*/

void preorder(bitree &t),p=null;

int top = 0;

p = t;

do if(top==0)else

}while(1);

}/*中序遞迴遍歷*/

void inorderrec(bitree &t)

}/*中序非遞迴遍歷*/

void inorder(bitree &t),p=null;

p = t;

int top = 0;

do if(top==0)else

}while(1);

}/*後序遞迴遍歷*/

void postorderrec(bitree &t)

}/*後序非遞迴遍歷*/

void postorder(bitree &t),p=null;

int top = 0,mark[max_len]=;

p = t;

do if(0==top)elseelse

} }while(1);

}int main()

驗證:a

/\bc

/\dh\e

/\f g

執行結果:

二叉樹建立和遍歷

二叉樹建立遍歷規則 1.先序 根 左 右 2.中序 左 根 右 3.後序 左 右 根 二叉樹定義和輔助函式如下 struct node void visit int data int indata 先序建立二叉樹 struct node createbitree 先序建立乙個二叉樹 return t...

二叉樹建立和遍歷

include include 帶返回值建立二叉樹 最簡單方法 節點資料結構 struct bs node typedef struct bs node tree tree head,p,root 建立二元查詢樹 有返回值的可以不傳參 沒有的話如何傳參 輸入0代表到了某個葉子節點 tree crea...

二叉樹建立和遍歷

二叉樹建立遍歷規則 1.先序 根 左 右 2.中序 左 根 右 3.後序 左 右 根 二叉樹定義和輔助函式例如以下 struct node void visit int data int indata 先序建立二叉樹 struct node createbitree 先序建立乙個二叉樹 return...