刷题--二叉树的镜像
来源:互联网 发布:文华源码函数 编辑:程序博客网 时间:2024/06/05 07:54
题目:请完成一个函数,输入一个二叉树,该函数输出它的镜像
那么什么是二叉树的镜像呢?我们其实可以从生活中得到启示,每个人早上起来都有找镜子的习惯,这样我们就会很容易想明白二叉树的镜像了,
如图两颗互为镜像的二叉树.
观察这颗二叉树我们会发现,这两颗二叉树的根节点相同,但是它们的左右两个子节点交换了位置.
步骤:
1:首先交换节点2和节点6
2:第二步:交换将节点1和节点3作为整体然后和节点5和节点6的整体交换
3:将 节点1和节点3交换,节点5和节点7交换这样所有子节点就完成了交换.
其实就是递归走子问题,如果有叶子节点,那么久将这两个叶子节点进行交换.
#include<iostream>#include<assert.h>using namespace std;template<class T>struct BSTreeNode{ T _data; BSTreeNode<T>*left; BSTreeNode<T>*right; BSTreeNode(const T& data =T()) :_data(data) , left(NULL) , right(NULL) {}};template<class T>class BSTree{ typedef BSTreeNode<T> Node;public: BSTree() :_root(NULL) {} ~BSTree() { _Destory(_root); } BSTree(T *a, size_t n, const T&invalid = T()) { size_t index = 0; _root = _Creat(a, n, index, invalid); } //二叉树的镜像 void MirrorBSTree() { _MirrorBSTree(_root); }private: void _Destory(Node*root) { if(root ==NULL) _Destory(root->left); _Destory(root->right); delete root; root =NULL; } Node*_Creat( T*a, size_t n, size_t &index, const T&invalied) { assert(a&&n>0); Node*root = NULL; if (n > index&&a[index] != invalied) { root = new Node(a[index]); root->left = _Creat(a, n, ++index, invalied); root->right = _Creat(a, n, ++index, invalied); } return root; } void _MirrorBSTree(Node*root) { if (root == NULL) { return; } if (root->left == NULL&&root->right == NULL) { return; } //将左右两个子节点进行交换 Node*tmp = root->left; root->left = root->right; root->right = tmp; //递归走子问题 if (root->left) { _MirrorBSTree(root->left); } if (root->right) { _MirrorBSTree(root->right); } }private: Node*_root;};int main(){ int a1[] = { 4, 2, 1, '#', '#', 3, '#', '#', 6, 5 ,'#','#',7}; size_t sz = sizeof(a1) / sizeof(a1[0]); BSTree<int> bt(a1,sz,'#'); bt.MirrorBSTree(); system("pause"); return 0;}
阅读全文
0 0
- 刷题--二叉树的镜像
- 刷题--二叉树的镜像
- 二叉树的镜像
- 二叉树的镜像
- 二叉树的镜像
- 二叉树的镜像
- 二叉树的镜像
- 二叉树的镜像
- 二叉树的镜像
- 二叉树的镜像
- 二叉树的镜像
- 二叉树的镜像
- 二叉树的镜像
- 二叉树的镜像
- 二叉树的镜像
- 二叉树的镜像
- 二叉树的镜像
- 二叉树的镜像
- Java实现邮箱激活账户实例
- lua中的编译执行和错误
- 无人驾驶好文
- 基于循环神经网络实现基于字符的语言模型(char-level RNN Language Model)-tensorflow实现
- SVM支持向量机
- 刷题--二叉树的镜像
- Linux系统-tcpdump常用抓包命令
- MySQL 分组
- 【Eternallyc】素数6N+1法
- jquery方法1
- android中sharedPreferences的用法
- 买了台thinkpad x230敲代码学习
- 泛型的反射
- Linux定时任务-crond