二叉树的镜像
2016-06-30 20:43
295 查看
题意描述:输入一个二叉树,写函数实现输出该二叉树的镜像。二叉树的定义如下:
即将下图的左边的树转换成右边的树:
解题思路:先想只有三个结点的树,做法是交换左右子结点,即求得这样三个结点的树的镜像。同理对于二叉树,采用递归方式即可:
struct BinaryTreeNode { int m_nValue; BinaryTreeNode* m_pLeft; BinaryTreeNode* m_pRight; };
即将下图的左边的树转换成右边的树:
解题思路:先想只有三个结点的树,做法是交换左右子结点,即求得这样三个结点的树的镜像。同理对于二叉树,采用递归方式即可:
//方法一:无返回值 void mirrorRecursively(BinaryTreeNode* root) { if (root == NULL) return; if (root->m_pLeft == NULL && root->m_pRight == NULL) return ; BinaryTreeNode* tempNode = root->m_pLeft; root->m_pLeft = root->m_pRight; root->m_pRight = tempNode; if (root->m_pLeft) mirrorRecursively(root->m_pLeft); if (root->m_pRight) mirrorRecursively(root->m_pRight); }
//方法二:返回镜像后的头结点 BinaryTreeNode* mirrorRecursively2(BinaryTreeNode* root) { if (root == NULL) return NULL; BinaryTreeNode* tempNode = root->m_pLeft; root->m_pLeft = mirrorRecursively2(root->m_pRight); root->m_pRight = mirrorRecursively2(tempNode); return root; }
相关文章推荐
- 倒计时练习
- Linux 下网络相关命令
- keil 之map文件应用
- 外网主机访问虚拟机中的部署在tomcat上的web项目
- hadoop中mr处理大量小文件
- GUI编程 action事件
- Nginx搭建图片服务器(Windows)
- 比较练习
- 如何查看Apache的configure编译参数
- stm32 keil debug 调试笔记二
- 会话控制
- PullRefreshGridView 下拉刷新,上拉加载
- Swift网络封装库Moya中文手册之Endpoints
- Codeforces Round #360 (Div. 2) E. The Values You Can Make DP
- 大数加法
- Values目录下的colors.xml内容
- XListView+圆头像
- docker与虚拟机性能比较
- [rsync+inotify]——监控客户端文件变化,rsync同步到服务器
- javascript “||”、“&&”的灵活运用