《剑指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
- 【剑指offer】二叉树的镜像
- [剑指Offer]二叉树的镜像
- 剑指offer--二叉树的镜像
- 剑指Offer-二叉树的镜像
- 《剑指offer》二叉树的镜像
- 剑指 offer:二叉树的镜像
- 【剑指offer】二叉树的镜像
- 剑指offer 二叉树的镜像
- [剑指offer]二叉树的镜像
- 《剑指offer》-二叉树的镜像
- 剑指Offer:二叉树的镜像
- 剑指offer|二叉树的镜像
- 《剑指offer》二叉树的镜像
- 剑指Offer:二叉树的镜像
- 【剑指offer】二叉树的镜像
- 剑指Offer:二叉树的镜像
- 剑指offer-二叉树的镜像
- 剑指offer 二叉树的镜像
- 这样投简历,99%没面试机会!
- php 中文分词使用
- 第14周-阅读程序(3)
- mac查看端口号占用
- cx_Oracle安装 评分卡完善 2016.06.06回顾
- 《剑指offer》:[19]二叉树的镜像
- [ABAP] The type "slis_formname"is unknown.
- C/C++ - 基础知识
- Java多线程(三)
- 如何分训练集和测试集,如何算召回率和准确率?
- 第15周-阅读程序(1)
- 人与人的差距是如何拉开的?
- IOS AVAudioRecorder 录制音频
- webservice高级,安全(附带实例)