1. 程式人生 > >二叉查詢樹/二叉排序樹/二叉搜尋樹----> BST

二叉查詢樹/二叉排序樹/二叉搜尋樹----> BST

二叉查詢樹/二叉排序樹/二叉搜尋樹—-> BST

基本操作:查詢、插入、建樹、刪除。

//二叉查詢樹/二叉排序樹/二叉搜尋樹---->  BST 


//基本操作:查詢、插入、建樹、刪除。




//search 函式查詢二叉查詢樹中資料域為x的結點

void search(node* root,int x)
{
    if(root == NULL)
    {
        printf("search failed\n");
        return;
    }

    if(x==root->data)       //查詢成功,訪問 
    {
        printf("%d\n"
,root->data); } else if(x<root->data) { search(root->lchild,x); //往左子樹遞迴搜尋x } else { search(root->rchild,x); //往右子樹遞迴搜尋x } } //insert函式將在二叉樹中插入一個數據域為x的新結點(注意引數root 要加引用&) void insert(node* &root,int x) { if(root==NULL
) //空樹,說明查詢失敗,也就是插入位置 { root=new_node(x); return; } if(x==root->data) //查詢成功,說明結點已存在,直接返回 { return; } else if(x<root->data) //如果x比根結點的資料域小,說明x需要插在左子樹中 { insert(root->lchild,x); } else { insert(root->rchild,x); } } //二叉查詢樹的建立 node
* create(int data[],int n) { node* root=NULL; //新建根結點root for(int i=0;i<n;i++) { insert(root,data[i]); //將data[0]~data[n-1]插入二叉查詢樹中 } return root; } //尋找以root為根結點的樹中的最大權值結點 node* find_max(node* root) { while(root->rchild !=NULL) { root=root->rchild; } return root; } //尋找以root為結點的樹中的最小權值點 node* find_min(node* root) { while(root->lchild!=NULL) { root=root->lchild; } return root; } //刪除以root為根結點的樹中權值x的結點 //兩種方案:1.以x的前驅代替x,並且刪除x的前驅; // 2.以x的後繼代替x,並且刪除x的後繼; void delete_node(node* &root,int x) { if(root==NULL) //不存在權值為x的結點 { return; } if(root->data==x) //找到想要刪除的結點 { if(root->lchild==NULL && root->rchild ==NULL) //是葉子結點,直接刪除 { root=NULL; //把root地址設為NULL,父結點就引用不到它了。 } else if(root->lchild != NULL) { node* pre=find_max(root->lchild); //root前驅等於root左子樹中的最大值結點 root->data=pre->data; //用前驅覆蓋root delete_node(root->lchild,pre->data); //遞迴刪除前驅,彌補漏洞。 } else { node* next=find_min(root->rchild); //root後繼等於root右子樹中的最小值結點 root->data=next->data; delete_node(root->rchild,next->data); //彌補後繼元素的漏洞 } } else if(root->data > x) { delete_node(root->lchild,x); //在左子樹刪除x } else { delete_node(root->rchild,x); //往右子樹刪除x } }