1. 程式人生 > >樹的鏡向

樹的鏡向

問題:

    求一顆樹的鏡向


解決思路:

    鏡向其實就是將所有結點的左右兩個子結點交換就行。所以可以遍歷二叉樹,遍歷到一個結點時,交換其左右兩個子結點。


程式碼:

遞迴版本

void Mirro(BTree *T)
{
	if (T == NULL || (T->left == NULL && T->right == NULL))
		return ;
	
	BTree *tmp = T->left;
	T->left = T->right;
	T->right = tmp;
	if (T->left != NULL)
		Mirro(T->left);
	if (T->right != NULL)
		Mirro(T->right);
}


非遞迴版本

void Mirro2(BTree *T)
{
	if (T == NULL || (T->left == NULL && T->right == NULL))
		return ;

	stack<BTree *> s;
	s.push(T);
	while (!s.empty())
	{
		BTree *tmp = s.top();
		s.pop();
		BTree *cur = tmp->left;
		tmp->left = tmp->right;
		tmp->right = cur;

		if (tmp->left != NULL)
			s.push(tmp->left);
		if (tmp->right != NULL)
			s.push(tmp->right);
	}
}