《剑指offer》:[19]二叉树的镜像

来源:互联网 发布:java多态 编辑:程序博客网 时间:2024/06/07 02:58
      对于比较复杂的算法和设计,一般来讲最好是在开始写代码前讲清楚思路和设计,举个例子或者画图都是很好的方法!-----尧敏
题目:请完成一个函数,输入一个二叉树,该函数输出它的镜像。

树的镜像对于很多人来说是一个新的概念,但是只要听说过一次就会发现其实很简单:就是将树以根结点为对称轴进行左右翻转。为了直观的了解,图示树(A)的镜像如下:


求二次函数镜像的过程:
我们先前序遍历这棵树的每个结点,如果遍历到结点有子结点,就交换它的两个子结点。当交换完所有非叶子结点之后,就得到了树的镜像。
具体实现代码如下:
#include <iostream>using namespace std;struct BinaryTree{int data;BinaryTree *pLeft;BinaryTree *pRight;};void InsertTree(BinaryTree*root,int data);void CreateTree(BinaryTree **root,int *array,int length);void PreOrder(BinaryTree *tree);void MirrorRecursive(BinaryTree *root);void Destory(BinaryTree *root);BinaryTree *pRoot1=NULL;int arr[7]={8,6,12,5,7,9,14};void CreateTree(BinaryTree **root,int *array,int length){for(int i=0;i<length;i++){if(NULL==*root){BinaryTree *pNode=new BinaryTree;pNode->data=array[i];pNode->pLeft=pNode->pRight=NULL;*root=pNode;}else{InsertTree(*root,array[i]);}}}void InsertTree(BinaryTree*root,int data){//看在左边和右边;if(root->data >data){if(NULL==root->pLeft){BinaryTree *pNode=new BinaryTree;pNode->data=data;pNode->pLeft=pNode->pRight=NULL;root->pLeft=pNode;}else{InsertTree(root->pLeft,data);}}else//在右边;{if(NULL==root->pRight){BinaryTree* pNode=new BinaryTree;pNode->data=data;pNode->pLeft=pNode->pRight=NULL;root->pRight=pNode;}else{InsertTree(root->pRight,data);}}}void PreOrder(BinaryTree *tree){BinaryTree *temp=tree;if(temp){cout<<temp->data<<" ";PreOrder(tree->pLeft);PreOrder(tree->pRight);}}void Destory(BinaryTree *root){if(root){Destory(root->pLeft);Destory(root->pRight);delete root;root=NULL;}}void MirrorRecursive(BinaryTree *root){if(NULL==root)return;if(NULL==root->pLeft && NULL==root->pRight)return;//交换两个结点;BinaryTree *temp=root->pLeft;root->pLeft=root->pRight;root->pRight=temp;if(root->pLeft)MirrorRecursive(root->pLeft);if(root->pRight)MirrorRecursive(root->pRight);}int main(){CreateTree(&pRoot1,arr,7);PreOrder(pRoot1);cout<<endl;MirrorRecursive(pRoot1);PreOrder(pRoot1);cout<<endl;Destory(pRoot1);system("pause");return 0;}

运行结果:




0 0
原创粉丝点击