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

数据结构与算法分析——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);
				else
					father = 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);
				}
				else
					father = doubleRotateWithLeft(father);
			}
			route.push(father);
		}
		father->height = Max(height(father->left), height(father->right)) + 1;
	}

	
	
}


你可能感兴趣的:(AVL树进行插入的非递归函数)