搜索二叉树的数据结构定义:
/*二叉搜索树的结构定义*/ typedef struct TreeNode* SearchTree; typedef struct TreeNode* Position; struct TreeNode { int Element; SearchTree Left; SearchTree Right; }
SearchTree Insert(int x, SearchTree T) { if(T == NULL)//空树 { T = malloc(sizeof(struct TreeNode)); if(T == NULL) { printf("Out of space!"); return NULL; } else { T->Element = x; T->Left = T->Right = NULL; } } else if(x < T->Element) T->Left = Insert(x, T->Left); else if(x > T->Element) T->Right = Insert(x, T->Right); /*如果x已在树中,就什么也不做*/ return T; }
SearchTree Delete(int x, SearchTree T) { SearchTree parent_p, p, q, r; p = T; parent_p = NULL; while(p)//查找关键字为x的结点 { if(p->Element == x) break; f = p; if(p->Element < x) p = p->Right; else p = p->Left; } if(p == NULL)//如果没找到,直接返回原二叉搜索树 return T; if(p->Left == NULL)//p无左孩子 { if(parent_p == NULL)//p为原二叉搜索树的根 T = T->Right; else if(f->Left == p)//p为左孩子 f->Left = p->Right; else //p为右孩子 f->Right = p->Right; p->Right = NULL//避免野指针问题 free(p); } else//p有左孩子 { q = p; r = p->Left; while(r->Right)//寻找p的左子树中最大的结点来代替p { q = r; r = r->Right; } if(q == p) q->Left = r->Left; else q->Right = r->Left; p->Element = r->Element; r->Left = NULL;//避免野指针问题 free(r); } return T; }
原文:http://blog.csdn.net/wan_hust/article/details/25004863