二叉树的镜像

来源:互联网 发布:供应商数据分析 编辑:程序博客网 时间:2024/05/19 17:58

/*
面试题19:二叉树的镜像
输入一个二叉树,输出它的镜像。
*/
解题思路:
先前序遍历树的每一个节点,如果遍历到的结点有子节点,就交换它的两个子节点。当交换完所有非叶子结点的左右子节点之后,就得到了树的镜像。

struct BinaryTreeNode{    int                 m_nValue;    BinaryTreeNode*     m_pLeft;    BinaryTreeNode*     m_pRight;};BinaryTreeNode* Create(){    BinaryTreeNode *pRoot;    int data;    cin>>data;    if(data ==0)    {        pRoot = NULL;    }    else    {        pRoot = new BinaryTreeNode;        pRoot->m_nValue = data;        pRoot->m_pLeft = Create( );        pRoot->m_pRight = Create( );    }    return pRoot;}void PreOrder(BinaryTreeNode* pRoot){    if(pRoot)    {        cout<<pRoot->m_nValue <<" ";        PreOrder(pRoot->m_pLeft );        PreOrder(pRoot->m_pRight );    }}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 )        MirrorRecursively(pNode->m_pLeft );    if(pNode->m_pRight )        MirrorRecursively(pNode->m_pRight );}int main(){    BinaryTreeNode* pRoot = NULL;    cout<<"The Tree is:"<<endl;    pRoot= Create();    cout<<"先序遍历:";    PreOrder(pRoot);    cout<<endl;    MirrorRecursively(pRoot);    cout<<"树的镜像先序遍历为:"<<endl;    PreOrder(pRoot);    cout<<endl;}
原创粉丝点击