二叉搜尋樹的基本操作

2021-07-27 20:03:04 字數 1719 閱讀 9617

建立乙個非負二叉搜尋樹(-1表空結點),編寫查詢函式,層序遍歷函式,插入函式,刪除函式,查詢最大值最小值函式

輸入該樹和要查詢的值

輸出:

如果找到,列印出

x is found

沒找到列印出 not found

列印出層序遍歷序列

刪除最大值和最小值

刪除成功輸出

x is delete

最後再進行一層序遍歷

例如:

輸入樣例:

8 5 3 -1 4 -1 -1 7 -1 -1 15 11 10 -1 -1 12 -1 -1 16 -1 -1

輸出樣例:

input what you want to find: 4

4 is found

levelorder: 8 5 15 3 7 11 16 4 10 12

16 is delete

3 is delete

levelorder: 8 5 15 4 7 11 10 12

#include #include #include using namespace std;

typedef struct bstnode* pbst;

queueq;

struct bstnode

*root;

pbst insert(int x,pbst t)//插入

else

if(x>t->data)

t->right=insert(x,t->right);

else

t->left=insert(x,t->left);

return t;

}pbst creat(pbst t)//建樹

return t;

}pbst find(pbst t,int x)//查詢

return null;

}pbst findmin(pbst t)//找最小值

pbst findmax(pbst t)//找最大值

pbst del(int x,pbst t)//刪除

else

}return t;

}void levelorder(pbst t)//層序遍歷 }}

int main() {

int n;

pbst t;

root=creat(root);

cout<

cin>>n;

t=find(root,n);

if(t)

cout

t=findmin(root);

cout

cout<

levelorder(root);

cout<

二叉搜尋樹的基本操作

二叉搜尋樹 binary search tree 它或者是一棵空樹,或者是具有下列性質的二叉樹 若它的左子樹不空,則左子樹上所有結點的值均小於它的根結點的值 若它的右子樹不空,則右子樹上所有結點的值均大於它的根結點的值 它的左 右子樹也分別為二叉搜尋樹樹。節點設定 typedef int datat...

二叉搜尋樹的基本操作

pragma once typedef int datatype typedef struct bstreenode bstnode include include include bstnode buybstreenode datatype data pnewnode data data pnew...

二叉搜尋樹的基本操作

binsearchtree.h typedef int datatype typedef struct bstreenode bstnode,pbstnode 初始化二叉搜尋樹 void initbstree bstnode proot 生成新節點 pbstnode buynewnode datat...