码迷,mamicode.com
首页 > 编程语言 > 详细

二叉排序树的创建删除中序输出

时间:2016-06-13 13:14:13      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:

#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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!