题目:请完成一个函数,输入一个二叉树,该函数输出它的镜像 代码
#include<iostream> #include<cstdlib> using namespace std; struct BinTreeNode { int _value; BinTreeNode* _pLeft; BinTreeNode* _pRight; BinTreeNode(int x) :_value(x) ,_pLeft(NULL) ,_pRight(NULL) {} }; class BinTree { public: BinTree() :_root(NULL) {} ~BinTree() { delete _root; _root=NULL; } BinTree(int * a,int size,const int& invalid) { int index=0; _createBinTree(_root,a,size,index,invalid); } void Proder() { _Proder(_root); cout<<endl; } void MirrorRecursively() { _MirrorRecursively(_root); } protected: void _MirrorRecursively(BinTreeNode* root) { if (root==NULL) return; if (root->_pLeft==NULL&&root->_pRight==NULL) return; BinTreeNode* tmp=root->_pLeft; root->_pLeft=root->_pRight; root->_pRight=tmp; if(root->_pLeft) _MirrorRecursively(root->_pLeft); if (root->_pRight) _MirrorRecursively(root->_pRight); } void _createBinTree(BinTreeNode*& root,int a[],int size,int &index,int invalid) { if(index<size&&a[index]!=invalid) { root=new BinTreeNode(a[index]); _createBinTree(root->_pLeft,a,size,++index,invalid); _createBinTree(root->_pRight,a,size,++index,invalid); } } void _Proder(BinTreeNode* root) { if(root==NULL) return; cout<<root->_value<<" "; _Proder(root->_pLeft); _Proder(root->_pRight); } private: BinTreeNode* _root; }; void test() { int arr[]={8,6,5,'#','#',7,'#','#',10,9,'#','#',11}; BinTree t1(arr,13,'#'); t1.Proder(); t1.MirrorRecursively(); t1.Proder(); } void test2() { int arr[]={8,6,5,'#','#',7}; BinTree t1(arr,6,'#'); t1.Proder(); t1.MirrorRecursively(); t1.Proder(); } #include "BinTree.h" int main() { test(); test2(); system("pause"); return 0; }test所用的二叉树 test2所用二叉树