首页 > 其他 > 详细

二叉树镜像

时间:2014-03-22 21:15:00      阅读:710      评论:0      收藏:0      [点我收藏+]

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

bubuko.com,布布扣

思路

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

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

参考代码

bubuko.com,布布扣
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);
    }
}
bubuko.com,布布扣

注意

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

完整运行

bubuko.com,布布扣
#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

二叉树镜像,布布扣,bubuko.com

二叉树镜像

原文:http://www.cnblogs.com/kaituorensheng/p/3617858.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!