面试题27:二叉树的镜像

题目:请完成一个函数,输入一个二叉树,该函数输出它的镜像。

#include<iostream>
using namespace std;
struct BinaryTreeNode {
	int m_nValue;
	BinaryTreeNode* m_pLeft;
	BinaryTreeNode* m_pRight;
};
void MirrorOfBinaryTree(BinaryTreeNode* pRoot) {
        //思路:遍历每个节点 交换该节点左右子树
	if (pRoot == nullptr) {
		return;
	}
	if (pRoot->m_pLeft == nullptr && pRoot->m_pRight == nullptr) {
		return;
	}
	BinaryTreeNode* pTemp = pRoot->m_pLeft;
	pRoot->m_pLeft = pRoot->m_pRight;
	pRoot->m_pRight = pTemp;
	if (pRoot->m_pLeft!=nullptr) {
		MirrorOfBinaryTree(pRoot->m_pLeft);
	}
	if (pRoot->m_pRight != nullptr) {
		MirrorOfBinaryTree(pRoot->m_pRight);
	}
}
//测试代码==========================================================
BinaryTreeNode* CreateBinaryTreeNode(double nValue)
{
	BinaryTreeNode* pNode = new BinaryTreeNode();
	pNode->m_nValue = nValue;
	pNode->m_pLeft = nullptr;
	pNode->m_pRight = nullptr;

	return pNode;
}

void ConnectTreeNodes(BinaryTreeNode* pParent, BinaryTreeNode* pLeft, BinaryTreeNode* pRight)
{
	if (pParent != nullptr)
	{
		pParent->m_pLeft = pLeft;
		pParent->m_pRight = pRight;
	}
}

void DestroyTree(BinaryTreeNode* pRoot)
{
	if (pRoot != nullptr)
	{
		BinaryTreeNode* pLeft = pRoot->m_pLeft;
		BinaryTreeNode* pRight = pRoot->m_pRight;

		delete pRoot;
		pRoot = nullptr;

		DestroyTree(pLeft);
		DestroyTree(pRight);
	}
}
void PrintTree(BinaryTreeNode* pRoot) {
	if (pRoot != nullptr) {
		if (pRoot->m_pLeft != nullptr) {
			PrintTree(pRoot->m_pLeft);
		}
		if (pRoot->m_pRight != nullptr) {
			PrintTree(pRoot->m_pRight);
		}
		cout << pRoot->m_nValue << " ";
	}
}
int main() {
	BinaryTreeNode* pNode1 = CreateBinaryTreeNode(8);
	BinaryTreeNode* pNode2 = CreateBinaryTreeNode(6);
	BinaryTreeNode* pNode3 = CreateBinaryTreeNode(10);
	BinaryTreeNode* pNode4 = CreateBinaryTreeNode(5);
	BinaryTreeNode* pNode5 = CreateBinaryTreeNode(7);
	BinaryTreeNode* pNode6 = CreateBinaryTreeNode(9);
	BinaryTreeNode* pNode7 = CreateBinaryTreeNode(11);

	ConnectTreeNodes(pNode1, pNode2, pNode3);
	ConnectTreeNodes(pNode2, pNode4, pNode5);
	ConnectTreeNodes(pNode3, pNode6, pNode7);
	//PrintTree(pNode1);
	MirrorOfBinaryTree(pNode1);
	PrintTree(pNode1);
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值