1. 程式人生 > >二叉搜尋樹的插入,刪除,和中序遍歷

二叉搜尋樹的插入,刪除,和中序遍歷

構建一個值的型別為int的二叉搜尋樹,輸入N和M,然後進行N次插入操作,每次插入之後進行一次遍歷驗證程式碼正確性。然後進行M次刪除操作,每次刪除之後進行一次遍歷驗證程式碼正確性。

#include "bits/stdc++.h"
using namespace std;
typedef long long LL;
const int INF = 0x3f3f3f3f;
struct BST {
    int value;
    BST* lson;
    BST* rson;
}* root;
void remove(int value);
BST* init(int val) {
    BST
* point = (BST*)malloc(sizeof(BST)); point->value = val; point->lson = point->rson = NULL; return point; } void insert(int val) { BST* father = NULL; BST* now = root; while (now != NULL) { if (now->value == val) { return; } father
= now; if (now->value < val) { now = now->rson; } else { now = now->lson; } } if (father == NULL) { root = init(val); } else if (father->value < val) { father->rson = init(val); } else { father
->lson = init(val); } } /*這題的難點在於刪除一個節點,思路是: 當要刪除的節點右子樹不為空時,用右子樹中的最小值代替要刪除的節點的值,同時刪除右子樹中值最小的節點 否則右子樹為空,可以用左子樹代替當前位置 當要刪除的節點是唯一節點時,將root置為空 */ int findAndRemoveMin(BST* point) { while (point->lson != NULL) { point = point->lson; } int ans = point->value; remove(ans); return ans; } void remove(int value) { BST* father = NULL; BST* now = root; while (now != NULL) { if (now->value == value) { if (now->rson != NULL) { now->value = findAndRemoveMin(now->rson); } else { if (father == NULL) { root = NULL; } else if (now->value > father->value) { father->rson = now->lson; } else { father->lson = now->lson; } free(now); } return; } father = now; if (now->value < value) { now = now->rson; } else { now = now->lson; } } } //二叉搜尋樹中序遍歷後會得到一個升序數列,這裡用遞迴寫起來很方便; void ergodic(BST* point) { if (point == NULL) { return; } ergodic(point->lson); printf("%d ", point->value); ergodic(point->rson); } int main() { int N, M, value; scanf("%d%d", &N, &M); while (N--) { scanf("%d", &value); insert(value); ergodic(root); puts(""); } while (M--) { scanf("%d", &value); remove(value); ergodic(root); puts(""); } return 0; }