19. 镜像二叉树(C++版本)

使用二叉树的相关定义及函数在:二叉树最小结构(C++版本)

循环实现:

void MirrorBinaryTree(BinaryTreeNode* pRoot)
{
	if (nullptr == pRoot) return;
	std::queue<BinaryTreeNode*> datas;
	datas.push(pRoot);

	while (!datas.empty())
	{
		BinaryTreeNode* pCurNode = datas.front();
		datas.pop();

		if (nullptr == pCurNode->pLeft && nullptr == pCurNode->pRight) continue;
		std::swap(pCurNode->pLeft, pCurNode->pRight);
		if (pCurNode->pLeft != nullptr) datas.push(pCurNode->pLeft);
		if (pCurNode->pRight != nullptr) datas.push(pCurNode->pRight);
	}
}

void MirrorBinaryTree(MyBinaryTree& binTree)
{
	MirrorBinaryTree(binTree);
}

递归实现:

void MirrorBinaryTree(BinaryTreeNode* pRoot)
{
	if (nullptr == pRoot) return;
	if (nullptr == pRoot->pLeft && nullptr == pRoot->pRight) return;

	std::swap(pRoot->pLeft, pRoot->pRight);
	if (pRoot->pLeft != nullptr) MirrorBinaryTree(pRoot->pLeft);
	if (pRoot->pRight != nullptr) MirrorBinaryTree(pRoot->pRight);
}

void MirrorBinaryTree(MyBinaryTree& binTree)
{
	MirrorBinaryTree(binTree.pRoot);
}

你可能感兴趣的:(剑指offer)