数据结构与算法分析——c语言描述 练习4.13 答案
a
else if (cursorSpace[t].left && cursorSpace[t].right) { /* tempCell = findMin(cursorSpace[t].right); cursorSpace[t].element = cursorSpace[tempCell].element; cursorSpace[t].right = Delete(cursorSpace[t].element, cursorSpace[t].right); */ tempCell = findMax(cursorSpace[t].left); cursorSpace[t].element = cursorSpace[tempCell].element; cursorSpace[t].left = Delete(cursorSpace[t].element, cursorSpace[t].left); }
b
SearchTree Delete(ElementType X, SearchTree t) { static int wayToDelete; Position tempCell; if (t == 0) { Error("Element not found"); } else if (X < cursorSpace[t].element) cursorSpace[t].left = Delete(X, cursorSpace[t].left); else if (X > cursorSpace[t].element) cursorSpace[t].right = Delete(X, cursorSpace[t].right); else if (cursorSpace[t].left && cursorSpace[t].right) { if (wayToDelete) { wayToDelete = 0; tempCell = findMin(cursorSpace[t].right); cursorSpace[t].element = cursorSpace[tempCell].element; cursorSpace[t].right = Delete(cursorSpace[t].element, cursorSpace[t].right); } else { wayToDelete = 1; tempCell = findMax(cursorSpace[t].left); cursorSpace[t].element = cursorSpace[tempCell].element; cursorSpace[t].left = Delete(cursorSpace[t].element, cursorSpace[t].left); } } else { tempCell = t; if (cursorSpace[t].left == 0) t = cursorSpace[t].right; else if (cursorSpace[t].right == 0) t = cursorSpace[t].left; cursorDispose(tempCell); } return t; }
c
#include<stdlib.h> SearchTree Delete(ElementType X, SearchTree t) { Position tempCell; if (t == 0) { Error("Element not found"); } else if (X < cursorSpace[t].element) cursorSpace[t].left = Delete(X, cursorSpace[t].left); else if (X > cursorSpace[t].element) cursorSpace[t].right = Delete(X, cursorSpace[t].right); else if (cursorSpace[t].left && cursorSpace[t].right) { if (rand()%2) { tempCell = findMin(cursorSpace[t].right); cursorSpace[t].element = cursorSpace[tempCell].element; cursorSpace[t].right = Delete(cursorSpace[t].element, cursorSpace[t].right); } else { tempCell = findMax(cursorSpace[t].left); cursorSpace[t].element = cursorSpace[tempCell].element; cursorSpace[t].left = Delete(cursorSpace[t].element, cursorSpace[t].left); } } else { tempCell = t; if (cursorSpace[t].left == 0) t = cursorSpace[t].right; else if (cursorSpace[t].right == 0) t = cursorSpace[t].left; cursorDispose(tempCell); } return t; }