資料結構 樹的遍歷(遞迴遍歷)

2021-09-08 22:35:19 字數 2042 閱讀 4226

樹的遍歷--遞迴遍歷

#include#include

#include

typedef

struct

_treenodetreenode, *treenodepointer;

//先序遍歷

void

printroot(treenodepointer root)}

//中序遍歷

void

printroot2(treenodepointer root)}//

後序遍歷

void

printroot3(treenodepointer root)

}void

test2()

//初始化資料

memset(t1, 0, sizeof

(treenode));

t2 = (treenodepointer)malloc(sizeof

(treenode));

if (t2 ==null)

//初始化資料

memset(t2, 0, sizeof

(treenode));

t3 = (treenodepointer)malloc(sizeof

(treenode));

if (t3 ==null)

//初始化資料

memset(t3, 0, sizeof

(treenode));

t4 = (treenodepointer)malloc(sizeof

(treenode));

if (t4 ==null)

//初始化資料

memset(t4, 0, sizeof

(treenode));

t5 = (treenodepointer)malloc(sizeof

(treenode));

if (t5 ==null)

//初始化資料

memset(t5, 0, sizeof

(treenode));

//填充資料域

t1->data = 'a'

; t2->data = 'b'

; t3->data = 'c'

; t4->data = 'd'

; t5->data = 'e'

;

//建立樹之間的關係

t1->leftchild =t2;

t1->rightchild =t3;

t2->leftchild =t4;

t2->rightchild =null;

t3->leftchild =t5;

t3->rightchild =null;

//t5是t4的左孩子

t4->leftchild =null;

t4->rightchild =null;

//t5沒有孩子節點

t5->leftchild =null;

t5->rightchild =null;

//遞迴遍歷樹

printf("

先序遍歷\n");

printroot(t1);

printf("\n

");printf(

"中序遍歷\n");

printroot2(t1);

printf("\n

");printf(

"後序遍歷\n");

資料結構 樹的遍歷(遞迴遍歷練習)

樹的遍歷 練習 include include include typedef struct treenodetreenode,treenodepointer 計算葉子節點的數目 void leafcount treenodepointer root,int num 遍歷左子樹 leafcount ...

資料結構 樹非遞迴遍歷

這裡以二叉樹為乙個例子來進行樹的先序,中序,後序,層序,二叉樹的刪除操作。include include using namespace std typedef struct bitnodebitnode bitree bitnode newnode int ch void insert bitre...

資料結構 樹的遍歷

以前序遍歷為例 1 先遍歷樹根 2 然後前序遍歷左子樹 3 最後前序遍歷右子樹 對於這樣的乙個二叉樹 前序遍歷結果 abdegcf 遍歷流程 首先遍歷樹根,輸出a 對a的左子樹進行前序遍歷,怎麼前序遍歷?對於b這個左子樹而言,首先遍歷根節點,輸出b 然後遍歷子樹b的左子樹,得到d這個子樹,對d進行前...