二叉树镜像

镜像——照镜子得出的像。特征就是左右反着,如下图

思路

仿着递归遍历,递归得到镜像

  • 输入结点指针p不为空且部位叶子,反转p的左右孩子
  • 找p的左孩子的镜像
  • 找p的右孩子的镜像

参考代码

void getImage(BinaryTreeNode *root)
{
    if(root != NULL && root->m_pLeft != NULL && root->m_pRight != NULL)
    {
        BinaryTreeNode *temp = root->m_pLeft;
        root->m_pLeft = root->m_pRight;
        root->m_pRight = temp;
        getImage(root->m_pLeft);
        getImage(root->m_pRight);
    }
}

注意

有需要判断一下叶子结点(当然可以不判断是否为叶子,但是判断叶子两句,反转三句话)

完整运行

#include <iostream>
using namespace std;
struct BinaryTreeNode
{
    int m_nValue;
    BinaryTreeNode *m_pLeft;
    BinaryTreeNode *m_pRight;
};
void CreateTree(BinaryTreeNode *root)
{
    BinaryTreeNode *p1 = new(BinaryTreeNode);
    p1->m_nValue = 8;
    p1->m_pLeft = NULL;
    p1->m_pRight = NULL;
    root->m_pLeft = p1;

    BinaryTreeNode *p2 = new(BinaryTreeNode);
    p2->m_nValue = 7;
    p2->m_pLeft = NULL;
    p2->m_pRight = NULL;
    root->m_pRight = p2;

    BinaryTreeNode *p3 = new(BinaryTreeNode);
    p3->m_nValue = 9;
    p3->m_pLeft = NULL;
    p3->m_pRight = NULL;
    p1->m_pLeft = p3;

    BinaryTreeNode *p4 = new(BinaryTreeNode);
    p4->m_nValue = 2;
    p4->m_pLeft = NULL;
    p4->m_pRight = NULL;
    p1->m_pRight = p4;

    BinaryTreeNode *p5 = new(BinaryTreeNode);
    p5->m_nValue = 4;
    p5->m_pLeft = NULL;
    p5->m_pRight = NULL;
    p4->m_pLeft = p5;

    BinaryTreeNode *p6 = new(BinaryTreeNode);
    p6->m_nValue = 7;
    p6->m_pLeft = NULL;
    p6->m_pRight = NULL;
    p4->m_pRight = p6;
}
void MidTraverse(BinaryTreeNode *root)
{
    if(root != NULL)
    {
        MidTraverse(root->m_pLeft);
        cout << root->m_nValue << " ";
        MidTraverse(root->m_pRight);
    }
}

void DeleteTree(BinaryTreeNode *root)
{
    if(root != NULL)
    {
        DeleteTree(root->m_pLeft);
        DeleteTree(root->m_pRight);
        delete(root);
        root = NULL;
    }
}

void getImage(BinaryTreeNode *root)
{
    if(root != NULL && root->m_pLeft != NULL && root->m_pRight != NULL)
    {
        BinaryTreeNode *temp = root->m_pLeft;
        root->m_pLeft = root->m_pRight;
        root->m_pRight = temp;
        getImage(root->m_pLeft);
        getImage(root->m_pRight);
    }
}
int main()
{
    BinaryTreeNode *root = new(BinaryTreeNode);
    root->m_nValue = 8;
    root->m_pLeft = NULL;
    root->m_pRight = NULL;

    CreateTree(root);
    MidTraverse(root);
    cout << endl;

    getImage(root);

    MidTraverse(root);
    cout << endl;
    DeleteTree(root);
}
View Code

结果

9 8 4 2 7 8 7
7 8 7 2 4 8 9

posted @ 2014-03-22 17:42  jihite  阅读(1130)  评论(0编辑  收藏  举报