题目:
操作给定的二叉树,将其变换为源二叉树的镜像。
知识点:
- 无
注意:
无
代码实现:
遍历所有节点,交换当前节点的左右子节点,递归至叶子节点
/*二叉树镜像*/
void mirror(BinaryTreeNode *pRoot) {
//边界值或特殊情况
if (pRoot == nullptr) {
return;
}
//递归至叶子节点(即左右子都为空)
if (pRoot->m_pLeft == nullptr && pRoot->m_pRight == nullptr) {
return;
}
//交换左右子节点
BinaryTreeNode* temp = nullptr;
temp = pRoot->m_pLeft;
pRoot->m_pLeft = pRoot->m_pRight;
pRoot->m_pRight = temp;
//递归左子树、右子树
mirror(pRoot->m_pLeft);
mirror(pRoot->m_pRight);
}
int main()
{
BinaryTreeNode* pNodeA1 = CreateBinaryTreeNode(8);
BinaryTreeNode* pNodeA2 = CreateBinaryTreeNode(8);
BinaryTreeNode* pNodeA3 = CreateBinaryTreeNode(7);
BinaryTreeNode* pNodeA4 = CreateBinaryTreeNode(9);
BinaryTreeNode* pNodeA5 = CreateBinaryTreeNode(2);
BinaryTreeNode* pNodeA6 = CreateBinaryTreeNode(4);
BinaryTreeNode* pNodeA7 = CreateBinaryTreeNode(7);
ConnectTreeNodes(pNodeA1, pNodeA2, pNodeA3);
ConnectTreeNodes(pNodeA2, pNodeA4, pNodeA5);
ConnectTreeNodes(pNodeA5, pNodeA6, pNodeA7);
mirror(pNodeA1);
PrintTree(pNodeA1);
getchar();
return 0;
}