编程之递归
struct TreeNode; typedef struct TreeNode *Postion; typedef struct TreeNode *SearchTree; /// 经典之作 SearchTree MakeEmpty(SearchTree T); Postion Find(ElementType X, SearchTree T); Postion FindMin(SearchTree T); Postion FindMax(SearchTree T); SearchTree Insert(ElementType X, SearchTree T); SearchTree Delete(ElementType X, SearchTree T); ElementType Retrieve(Postion P); struct TreeNode { ElementType Element; SearchTree Left; SearchTree Right; }; SearchTree MakeEmpty(SearchTree T) { if (T != NULL) { MakeEmpty(T->Left); MakeEmpty(T->Right); free(T); } return NULL; } Postion Find(ElementType X, SearchTree T){ if (T == NULL) return NULL; if (X < T->Element) return Find(X, T-> Left); else if (X > T->Element) return Find(X, T->Right); else return T; } Postion FindMin(SearchTree T){ if (T == NULL) return NULL; else if (T->Left == NULL) return T; else return FindMin(T->Left); } Postion FindMax(SearchTree T){ // if (T == NULL) return NULL; // else if (T->Right == NULL) return T; // else return FindMax(T->Right); if (T!= NULL){ // 非递归 while(T->Right != NULL) { T = T->Right; } } return T; } SearchTree Insert(ElementType X, SearchTree T){ if(T == NULL){ T = malloc(sizeof(struct TreeNode)); if (T == NULL) FatalError("Out Of Space"); 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); } return T; } SearchTree Delete(ElementType X, SearchTree T){ // 此树删除效率不高 Postion TmpCell; if (T == NULL) { Error("Element Not Found") } else if (X < T->Element){ T->Left = Delete(X, T->Left); } else if(X > T->Element){ T->Right = Delete(X, T->Right); } else if(T->Left && T->Right){ // Two Chil TmpCell = FindMin(T->Right); T->Element = TmpCell->Element; T->Right = Delete(T->Element, T->Right) } else { // one or zero chil TmpCell = T; if (T->Left == NULL) { T = T->Right; } else if(T->Right == NULL){ T = T->Left; } free(TmpCell); } }
这段二叉查找树的代码,我个人特别喜欢,不得不说递归在二叉树方面应用的 就是那么优美,简单,虽然效率上比非递归的低,但是易读性不得不说,nice.
个人觉得这段代码有这个几个地方值得我们学习:
1. 严紧, 就但看if(T == NULL)就可以看出来
2. 单一, 每个函数所处理的东西直接了当,目的清晰明确
3. 简单而又不简单(递归),聪明的人比较擅长,表示个人不擅长