1. 程式人生 > >二叉搜尋樹找前驅和後繼

二叉搜尋樹找前驅和後繼

輸入N個數,找每個數的前驅和後繼。如果沒有前驅或後繼,輸出-1;

思路:

如果有右子樹,則右子樹的最小值為當前節點的後繼;否則後繼為當前節點往祖先搜尋,第一次是左孩子的節點的父親的值;

如果有左子樹,則左子樹的最大值為當前節點的前驅;否則前驅為當前節點往祖先搜尋,第一次是右孩子的節點的父親的值;

#include "bits/stdc++.h"
using namespace std;
typedef long long LL;
const int INF = 0x3f3f3f3f;
struct BST {
    int value;
    BST* father;
    BST
* lson; BST* rson; }* root; 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); root->father = NULL; } else if (father->value < val) { father
->rson = init(val); father->rson->father = father; } else { father->lson = init(val); father->lson->father = father; } } int minOfBST(BST* point) { while (point->lson != NULL) { point = point->lson; } return point->value; } int maxOfBST(BST* point) { while (point->rson != NULL) { point = point->rson; } return point->value; } int precursor (int val) { BST* point = root; while (point != NULL) { if (point->value == val) { if (point->lson != NULL) { return maxOfBST(point->lson); } else { while (point->father != NULL && point->father->rson != point) { point = point->father; } if (point->father == NULL){ return -1; } else { return point->father->value; } } } if (val > point->value) { point = point->rson; } else { point = point->lson; } } } int successor (int val) { BST* point = root; while (point != NULL) { if (point->value == val) { if (point->rson != NULL) { return minOfBST(point->rson); } else { while (point->father != NULL && point->father->lson != point) { point = point->father; } if (point->father == NULL){ return -1; } else { return point->father->value; } } } if (val > point->value) { point = point->rson; } else { point = point->lson; } } } int main() { int N, val; queue<int>q; scanf("%d", &N); while (N--) { scanf("%d", &val); insert(val); q.push(val); } while (!q.empty()) { printf("%d ", precursor(q.front())); printf("%d\n", successor(q.front())); q.pop(); } return 0; }