二叉樹的建立和遍歷

2021-10-05 09:20:29 字數 2668 閱讀 5925

/*

什麼是二叉搜尋樹

二叉搜尋樹又叫二叉排序樹或者二叉查詢樹

position find( elementtype x, bintree bst ):從二叉搜尋樹bst

中查詢元素x,返回其所在結點的位址;

position findmin( bintree bst ):從二叉搜尋樹bst中查詢並返回

最小元素所在結點的位址;

position findmax( bintree bst ) :從二叉搜尋樹bst中查詢並返回

最大元素所在結點的位址。

bintree insert( elementtype x, bintree bst )

bintree delete( elementtype x, bintree bst )

1 二叉樹的查詢操作:

從根節點開始,如果為空,返回null

若非空.則根節點關鍵字和x比較,並進行不同的處理

如果結果相同,搜尋完成,返回指向該節點的指標

重複23步驟

2:查詢二叉樹的最大和最小元素

最大元素一點是在最右分支的端節點上

最小元素一定時在最左分支的端接點上

3:二叉樹的插入操作

1:找到需要插入的位置

2:比他大就插入到右邊,小就插入到左邊

4:二叉樹的刪除操作:

當刪除的是葉節點時:

直接刪除,在修改父節點的指標,置為null

當要刪除的節點不是葉節點時:

只有乙個孩子時:

直接將要刪除節點的父節點指向要刪除節點的子節點

當有兩個孩子時:

用右子樹的最小樹或者左子樹的最大樹代替

*/#include

#include

//要完成的操作

/* 1:查詢操作

2:找到最大值和最小值

3:插入操作

4:刪除操作

*///定義結構體:

struct treenode

;treenode*

build_tree()

;void

show_imformation

( treenode *root)

;void

find_x

(treenode *root ,

int* max)

;void

find_max

(treenode *root ,

int* max)

;void

find_min

(treenode *root ,

int* max)

;//定義框架:

intmain

(void

)struct treenode*

build_tree()

//如果root沒有建立成功的話,就是記憶體分配不成功就不用往下了肯定有問題if(

!root)

//如果輸入的值大於0的話,就預設是有效的輸入

if(val >0)

//最後將第乙個節點返回就ok,最後由於是遞迴,所以肯定是第乙個節點

return root;

}//展示節點:

void

show_imformation

( treenode *root)

printf

("%d "

,root->val)

;show_imformation

(root->left)

;show_imformation

(root->right);}

void

find_x

(treenode *root ,

int* max)if(

*max == root->val)

find_x

(root->left , max)

;find_x

(root->right , max)

;// printf("\n此時的max是:\n%d" ,*max);

return;}

//findmin

void

find_max

(treenode *root ,

int* max)if(

*max < root->val)

find_max

(root->left , max)

;//printf("\n左指數此時的max是:\n%d" ,*max);

find_max

(root->right , max)

;// printf("\n右子樹此時的max是:\n%d" ,*max);

return;}

void

find_min

(treenode *root ,

int* max)if(

*max ==-1

)if(*max > root->val)

find_min

(root->left , max)

;//printf("\n左指數此時的max是:\n%d" ,*max);

find_min

(root->right , max)

;//printf("\n右子樹此時的max是:\n%d" ,*max);

return

;}

二叉樹建立和遍歷

二叉樹建立遍歷規則 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...