AVL树进行插入的非递归函数

来源:互联网 发布:linux坏了怎么卸载 编辑:程序博客网 时间:2024/06/06 04:00

数据结构与算法分析——c语言描述 练习4.19  答案


挺有意思的。改递归为非递归。其实原理还是一样,都用了栈。


AvlTree insert(ElementType X, AvlTree t) {AvlTree root = t;std::stack<AvlTree> route;while (1) {if (t == NULL) {t = (AvlTree)malloc(sizeof(struct AvlNode));if (t == NULL)Error("out of memory");t->element = X;t->left = NULL;t->right = NULL;t->height = 0;t->isDeleted = 0;route.push(t);break;}else if (X < retrieve(t)) {route.push(t);t = t->left;continue;}else if (X >retrieve(t)) {route.push(t);t = t->right;continue;}else {t->isDeleted = 0;return root;}}AvlTree father,son;while (1) {son = route.top();route.pop();if (route.empty())return son;father = route.top();route.pop();if (father->element < son->element) {//儿子在右边father->right = son;if (height(father->right) - height(father->left) == 2) {if (X > retrieve(father->right))father = singleRotateWithRight(father);elsefather = doubleRotateWithRight(father);}route.push(father);}else if (father->element > son->element) {//儿子在左边father->left = son;if (height(father->left) - height(father->right) == 2) {if (X < retrieve(father->left)) {father = singleRotateWithLeft(father);}elsefather = doubleRotateWithLeft(father);}route.push(father);}father->height = Max(height(father->left), height(father->right)) + 1;}}


0 0
原创粉丝点击