**题目:**请完成一个函数,输入一棵二叉树,该函数输出它的镜像。
分析:
仔细观察,可以看出,镜像是在原来树的基础上,对每个树的左右子树进行交换位置。
先前序遍历(根->左->右)这棵树的每个节点,如果遍历到的节点有子节点,就交换它的两个子节点。当交换完所有非叶子节点的左、右子节点之后,就得到了树的镜像。
代码:
public static class BinaryTreeNode{
int m_nValue;
BinaryTreeNode m_pLeft;
BinaryTreeNode m_pRight;
BinaryTreeNode(int m_nValue){
this.m_nValue=m_nValue;
}
}
public static void MirrorRecursively(BinaryTreeNode pNode){
if(pNode==null)
return;
if(pNode.m_pLeft==null&&pNode.m_pRight==null)
return;
BinaryTreeNode pTemp=pNode.m_pLeft;
pNode.m_pLeft=pNode.m_pRight;
pNode.m_pRight=pTemp;
if(pNode.m_pLeft!=null)
MirrorRecursively(pNode.m_pLeft);
if(pNode.m_pRight!=null)
MirrorRecursively(pNode.m_pRight);
}