您的位置:首页 > 其它

二叉树的镜像

2016-06-30 20:43 295 查看
题意描述:输入一个二叉树,写函数实现输出该二叉树的镜像。二叉树的定义如下:

struct BinaryTreeNode {
int m_nValue;
BinaryTreeNode* m_pLeft;
BinaryTreeNode* m_pRight;
};


即将下图的左边的树转换成右边的树:



解题思路:先想只有三个结点的树,做法是交换左右子结点,即求得这样三个结点的树的镜像。同理对于二叉树,采用递归方式即可:

//方法一:无返回值
void mirrorRecursively(BinaryTreeNode* root) {
if (root == NULL)
return;
if (root->m_pLeft == NULL && root->m_pRight == NULL)
return ;

BinaryTreeNode* tempNode = root->m_pLeft;
root->m_pLeft = root->m_pRight;
root->m_pRight = tempNode;

if (root->m_pLeft)
mirrorRecursively(root->m_pLeft);
if (root->m_pRight)
mirrorRecursively(root->m_pRight);
}
//方法二:返回镜像后的头结点
BinaryTreeNode* mirrorRecursively2(BinaryTreeNode* root) {
if (root == NULL)
return NULL;

BinaryTreeNode* tempNode = root->m_pLeft;
root->m_pLeft = mirrorRecursively2(root->m_pRight);
root->m_pRight = mirrorRecursively2(tempNode);

return root;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: