二叉树的镜像 【微软面试100题 第十五题】
来源:互联网 发布:vue.js pc端ui框架 编辑:程序博客网 时间:2024/06/06 18:58
题目要求:
输入一颗二元查找树(二元搜索树),将该树转换为它的镜像。
例如:
8 8
/ \ ---> / \
6 11 11 6
参考资料:剑指offer第20题
题目分析:
思路很简单:从根结点开始,交换左右结点的值,同时递归的处理左右子树。
代码中打印二叉树用到了分层遍历二叉树,见编程之美3.10.
代码实现:
#include <iostream>#include <queue>using namespace std;typedef struct BinaryTree{ struct BinaryTree *left,*right; int data;}BinaryTree;void initTree(BinaryTree **p);void MirrorRecursively(BinaryTree *root);void PrintTreeByLevel(BinaryTree *root);int main(void){ BinaryTree *root; initTree(&root); cout << "原二叉树:" << endl; PrintTreeByLevel(root); MirrorRecursively(root); cout << endl; cout << "镜像后的二叉树:" << endl; PrintTreeByLevel(root); return 0;}//分层遍历二叉树,见编程之美3.10void PrintTreeByLevel(BinaryTree *root){ if(root==NULL) return; queue<BinaryTree *> Q; Q.push(root); Q.push(0); while(!Q.empty()) { BinaryTree *tmp = Q.front(); Q.pop(); if(tmp) { cout << tmp->data << " "; if(tmp->left) Q.push(tmp->left); if(tmp->right) Q.push(tmp->right); } else if(!Q.empty()) { Q.push(0); cout << endl; } }}void MirrorRecursively(BinaryTree *root){ if(root == NULL) return; if(root->left == NULL || root->right == NULL) return; BinaryTree *tmp = root->left; root->left = root->right; root->right = tmp; if(root->left) MirrorRecursively(root->left); if(root->right) MirrorRecursively(root->right);}// 10// / \// 5 12// / \// 4 7void initTree(BinaryTree **p){ *p = new BinaryTree; (*p)->data = 10; BinaryTree *tmpNode = new BinaryTree; tmpNode->data = 5; (*p)->left = tmpNode; tmpNode = new BinaryTree; tmpNode->data = 12; (*p)->right = tmpNode; tmpNode->left = NULL; tmpNode->right = NULL; BinaryTree *currentNode = (*p)->left; tmpNode = new BinaryTree; tmpNode->data = 4; currentNode->left = tmpNode; tmpNode->left = NULL; tmpNode->right = NULL; tmpNode = new BinaryTree; tmpNode->data = 7; currentNode->right = tmpNode; tmpNode->left = NULL; tmpNode->right = NULL; }
0 0
- 二叉树的镜像 【微软面试100题 第十五题】
- 【从零单排之微软面试100题系列】15之二叉树的镜像
- 面试100题:15.求二叉树的镜像
- 面试100题:15.求二叉树的镜像
- 微软100题(15)镜像二叉树
- 【100题】第十五题(树的镜像问题)
- 微软面试100题系列---二叉查找树的反转
- 微软面试100题系列---二叉树的层次遍历
- 微软面试100题系列---二叉树的深度
- 程序员面试100题之十三:求二叉查找树的镜像
- 程序员面试100题之十三:求二叉查找树的镜像
- 微软等数据结构与算法面试100题第十五题
- 【剑指Offer面试编程题】题目1521:二叉树的镜像--九度OJ
- 剑指offer 19题 【面试思路】二叉树的镜像
- 《剑指offer》刷题笔记(面试思路):二叉树的镜像
- July 微软面试100题 第11题 求二叉树的最大距离
- July 微软面试100题 第16题 二叉树的层次遍历
- 微软面试100题之第11题 求二叉树中节点的最大距离
- Spring中使用MyBatis的简单配置
- 和为s的两个数字 【微软面试100题 第十四题】
- HTML5移动开发之路(20)—— AppCan开发环境
- 加载dll以及卸载dll相关的几个API
- PHP关于文件与目录(1) 写入文件 文件权限 三、锁定文件
- 二叉树的镜像 【微软面试100题 第十五题】
- 机房重构总结之步履蹒跚
- IOS中AVAudioRecorder录音问题
- Oracle HANGANALYZE 功能诊断 DB hanging
- 周杰伦1.2亿卫冕14年吸金王
- 从上往下打印二叉树 【微软面试100题 第十六题】
- EditText常用属性
- 比较全面的gdb调试命令
- static方法中不能调用非静态方法(easy)