二叉树面试题(二)---求一颗二叉树的镜像

一、二叉树的镜像就是一个树在镜子里的成像;好吧!初中的物理知识来了,哈哈,其实很简单,采用递归的方法求二叉树的镜像:
(1)如果树为空,直接返回NULL;
(2)如果树不为空,求其左子树和右子树的镜像,递归完成后,将左子树的镜像放在根结点的右边,将右子树的镜像放在根结点的左边;
二、图说
这里写图片描述
三:代码实现

#include<iostream>
using namespace std;
#include<assert.h>
template<class T>
struct TreeNode
{
    TreeNode( const T& data=T())
        :_data(data)
        ,_left(NULL)
        ,_right(NULL)
    {}
    int _data;
    TreeNode<T>* _left;
    TreeNode<T>* _right;
};

template<class T>
class BinaryTree 
{
  typedef  TreeNode<T>  Node;
public:
    BinaryTree()//无参构造函数
        :_root(NULL)
    {}
    BinaryTree(const T* arr,int sz,const T invalid)//有参构造函数
    {
        assert(arr);
        int index=0;//数组中的位置
        _root=BuildTree(arr,sz,invalid,index);
    }
    void Printf()//前序打印
    {
         _Printf(_root);
    }
    void  MirrorPrintf()//打印二叉树镜像
    {
        _Printf(_MirrorImage(_root));
    } 
protected:
    Node* BuildTree(const T* arr,int sz,const T invalid,int& index)//前序建树(别忘了index为引用)
    {
            if (index<sz && arr[index]!=invalid)//没有走完数组,且不是非法值
            {
                Node* root=new Node(arr[index]);
                root->_left=BuildTree(arr,sz,invalid,++index);
                root->_right=BuildTree(arr,sz,invalid,++index);
                return root;
            }
            return NULL;
    }

    void _Printf(Node* root)
    {
        if (root)
        {
            cout<<root->_data<<" ";
            _Printf(root->_left);
            _Printf(root->_right);
        }
    }

    Node* _MirrorImage(Node* root)//求一颗二叉树的镜像
    {
        if (NULL==root)//树为空
        {
            return NULL;
        }
        else//树不为空
        {
             Node* pleft=_MirrorImage(root->_left);
             Node* pright=_MirrorImage(root->_right);
             root->_left=pright;
             root->_right=pleft;
             return root;
        }

    }
private:
    Node*  _root;
};

测试代码:

void Test()
{
    int arr1[] = {1, 2, 3, '#', '#', 4, '#' , '#', 5, 6};
    int sz1=sizeof(arr1)/sizeof(arr1[0]);
    BinaryTree<int>  bt1(arr1,sz1,'#');//调用带有参数的构造函数
    cout<<"原始树的前序序列:";
    bt1.Printf();
    cout<<endl;
    cout<<"镜像树的前序序列:";
    bt1.MirrorPrintf();
    cout<<endl;
}

四、运行结果
这里写图片描述

O(∩_∩)O

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值