您的位置:首页 > 职场人生

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

2017-04-20 11:24 232 查看
一、二叉树的镜像就是一个树在镜子里的成像;好吧!初中的物理知识来了,哈哈,其实很简单,采用递归的方法求二叉树的镜像:

(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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  二叉树 面试题 递归