二叉查找树的创建,插入,搜索,查询后继
来源:互联网 发布:黄庭坚书法知乎 编辑:程序博客网 时间:2024/04/27 14:27
#include<stdio.h>#include<malloc.h>#define null NULLtypedef struct t{int key;struct t *left;struct t *right;struct t *parent;}tree;tree* insert(tree *t,int i){tree *p=null;tree *x=t;if(t==null){ printf("hello\n"); t=(tree *)malloc(sizeof(tree)); t->key=i; t->left=null; t->parent=null; t->right=null; return t;}else{ while(x!=null) { p=x; if(i<x->key) x=x->left; else x=x->right; } tree *y=(tree *)malloc(sizeof(tree)); y->key=i; y->left=null; y->parent=p; y->right=null; if(i<p->key) p->left=y; else p->right=y; return t;}}tree *search(tree *t ,int i){tree *x=t;while(x!=null && x->key!=i){if(x->key>i)x=x->left;elsex=x->right;}return x;}tree* findmax(tree *t){tree *x=t;while(x->right!=null){x=x->right;}return x;}tree* findmin(tree *t){tree *x=t;while(x->left!=null){x=x->left;}return x;}tree* findsuccessor(tree *x)//找后继{tree *y=x;if(y->right!=null){return findmin(y->right);}else{tree *p=y->parent;while(p!=null && y==p->right){y=p;p=y->parent;}return p;}}void inorderprint(tree* t){if(t!=null){inorderprint(t->left);printf("%d ",t->key);inorderprint(t->right);}}void main(){tree *t=null;t=insert(t,15); t=insert(t,6);t=insert(t,18);t=insert(t,3);t=insert(t,7);t=insert(t,17);t=insert(t,20);t=insert(t,2);t=insert(t,4);t=insert(t,13);t=insert(t,9);inorderprint(t);printf("\n"); tree *x=search(t,15);if(x!=null){tree * h=findsuccessor(x);printf("the node value after searchd node is %d\n",h->key);}else if(x==null){printf("not find this node!\n");}}