输入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; }
原文地址:https://www.cnblogs.com/Angel-Demon/p/10222685.html
时间: 2024-11-05 15:56:53