标签:
#include<iostream> #include<cstdio> #include<cstring> #include<cmath> #include<algorithm> using namespace std; typedef struct Node{ Node *l, *r; int v; Node(){l = NULL; r = NULL;} }*tree, Node; tree build(tree p, int v){ if(p == NULL){ p = new Node(); p->v = v; return p; } if(v < p->v) p->l = build(p->l, v); else if(v > p->v) p->r = build(p->r, v); else return p; return p; } void Delete(tree &T, int k){ Node *p = T; Node *q, *s, *f; f = NULL; while(p){ if(p->v == k){ break; } f = p; if(k < p->v){ p = p->l; } else{ p = p->r; } } q = p; if(!p)return; if(p->l && p->r){ p = p->l; while(p->r){ s = p; p = p->r; } q->v = p->v; s->r = p->l; delete(p); return; } else if(p->l){ q = p; p = p->l; } else{ q = p; p = p->r; } //cout << "*" << endl; if(!f)T = p; else if(q == f->l)f->l = p; else f->r = p; delete(q); } void InOrder(tree p){ if(p == NULL)return; InOrder(p->l); printf("%d ", p->v); InOrder(p->r); } int main(){ int N; while(~scanf("%d", &N)){ tree p; p = NULL; int v; for(int i = 0; i < N; i++){ scanf("%d", &v); p = build(p, v); } InOrder(p); int m; scanf("%d", &m); for(int i = 0; i < m; i++){ scanf("%d", &v); Delete(p, v); InOrder(p); } } return 0; }
http://blog.csdn.net/zitong_ccnu/article/details/11097663#
标签:
原文地址:http://www.cnblogs.com/handsomecui/p/5579993.html