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

2021-09-08 22:35:19 字數 2832 閱讀 6153

//

樹的遍歷--練習

#include#include

#include

typedef

struct

_treenodetreenode, *treenodepointer;

//計算葉子節點的數目

void leafcount(treenodepointer root,int *num)

//遍歷左子樹

leafcount(root->leftchild, num);

//遍歷右子樹

leafcount(root->rightchild, num);

}}//

計算樹的深度

intdepth(treenodepointer root)

//獲取左子樹的深度

depthleft = depth(root->leftchild);

//獲取右子樹的深度

depthright = depth(root->rightchild);

//取左右兩個子樹的最大值 +1 因為根節點自己算一層

depthvalue = 1 + (depthleft>depthright ?depthleft : depthright);

return

depthvalue;}//

遍歷樹void

inorder(treenodepointer root)}//

拷貝樹treenodepointer copytree(treenodepointer root)

//先拷貝根節點

treenodepointer newroot = null, newleftnode = null, newrightnode =null;

newroot = (treenodepointer)malloc(sizeof

(treenode));

memset(newroot,

0, sizeof

(treenode));

if (newroot==null)

newroot->data = root->data;

//拷貝左子樹

newleftnode = copytree(root->leftchild);

//拷貝右子樹

newrightnode = copytree(root->rightchild);

newroot->leftchild =newleftnode;

newroot->rightchild =newrightnode;

return

newroot;}//

銷毀樹---後序遍歷比較合適,銷毀了根節點就找不著子節點了

void destroytree(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;

//獲取葉子節點的數目

//獲取樹的深度

//樹的拷貝

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

樹的遍歷 遞迴遍歷 include include include typedef struct treenodetreenode,treenodepointer 先序遍歷 void printroot treenodepointer root 中序遍歷 void printroot2 treeno...

資料結構 樹非遞迴遍歷

這裡以二叉樹為乙個例子來進行樹的先序,中序,後序,層序,二叉樹的刪除操作。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進行前...