AVL平衡树插入非递归实现 C语言

看了数据结构与算法树一章,决心写出AVL平衡树非递归插入算法。折腾两个晚上终于弄完,其中用到了C++中的栈模板,实在不想在写一个栈了。 总体实现思路如下:1. 若为空直接创建树2. 查找插入位置3. 插入4. 计算新树节点高度5.平衡新树
  
     AvlTree InsertWithoutRecursion(int X, AvlTree T)
     {
        /** insert node into AVL tree with out recursion */
	if (NULL == T)
	{
		T = (AvlTree)malloc(sizeof(AvlNode));
		if(NULL == T)
		{
			printf("Out of range...\n");
			return NULL;
		}
		T->Element = X;
		T->Left = T->Right = NULL;
		T->Height = 0;
		return T;
	}

	/** find insert pos */
	std::stack tail;
	/*	NodeT nodeTmp;*/
	Position ParentNode = T;	

	while (ParentNode != NULL)
	{
		tail.push(ParentNode);		
		if (X == ParentNode->Element)
		{
			return T;
		} 
		else if (X < ParentNode->Element)
		{
			if (ParentNode->Left == NULL)
			{
				break;
			} 
			else
			{
				ParentNode = ParentNode->Left;
			}
		}
		else
		{
			if (ParentNode->Right == NULL)
			{
				break;
			} 
			else
			{
				ParentNode = ParentNode->Right;
			}
		}
	}

	/** insert */
	AvlTree newNode = (AvlTree)malloc(sizeof(AvlNode));
	if (newNode == NULL)
	{
		printf("Out of range...");
		return T;
	}
	newNode->Element = X;
	newNode->Left = newNode->Right = NULL;
	newNode->Height = 0;
	if (X > ParentNode->Element)
	{
		ParentNode->Right = newNode;
	} 
	else
	{
		ParentNode->Left = newNode;
	}
	
	/**  */

	/** balance the tree */
	while (!tail.empty())
	{
		Position son = tail.top();
		tail.pop();
		son->Height = MAX(Height(son->Left), Height(son->Right)) + 1;
		Position father = tail.empty() ? NULL : tail.top();
		int dis = Height(son->Left) - Height(son->Right);
			
		if (dis == 2)
		{
			if (X < son->Left->Element)
			{
				if (father != NULL)
				{
					Position *P = father->Element < son->Element ? &father->Right : &father->Left;
					*P = SingleRotateWithLeft(son);
				}
				else
				{
					T = SingleRotateWithLeft(son);
				}
			} 
			else
			{
				if (father != NULL)
				{
					Position *P = father->Element < son->Element ? &father->Right : &father->Left;
					*P = DoubleRotateWithLeft(son);
				}
				else
				{
					T = DoubleRotateWithLeft(son);
				}
			}
		} 
		else if (dis == -2)
		{
			if (X > son->Right->Element)
			{
				if (father != NULL)
				{
					Position *P = father->Element < son->Element ? &father->Right : &father->Left;
					*P = SingleRotateWithRight(son);
				}
				else
				{
					T = SingleRotateWithRight(son);
				}
			} 
			else
			{
				if (father != NULL)
				{
					Position *P = father->Element < son->Element ? &father->Right : &father->Left;
					*P = DoubleRotateWithRight(son);
				}
				else
				{
					T = DoubleRotateWithRight(son);
				}
			}
		}
		if (NULL != father)
		{
			father->Height = MAX(Height(father->Left), Height(father->Right)) + 1;
		}
	}
	return T;
}


 
 

你可能感兴趣的:(数据结构)