二叉树的镜像20
来源:互联网 发布:淘宝正版洛丽塔 编辑:程序博客网 时间:2024/06/06 11:43
画图让抽象问题形象化:画图是用来帮助自己分析、推理的常用手段,当问题比较抽象时,不如画出一些与题目相关的图形,辅助自己观察和思考。图形能使抽象的问题具体化、形象化。空想未必能找到题目中隐含的规律和特点。
题目描述:请完成一个函数,输入一个二叉树,该函数输出它的镜像。
二叉树结点定义:
struct BinTreeNode{ int m_value; BinTreeNode *left; BinTreeNode *right; //创建根节点,值为e BinTreeNode* createRoot(int e); //将e作为当前结点的左孩子值插入 void insertAsLC(int e); //将e作为当前结点的右孩子值插入 void insertAsRC(int e);};
示例图片:
测试用例:
int main(){ //创建一颗二叉树 BinTreeNode *tree = new BinTreeNode; tree->m_value = 8; tree->insertAsLC(6); //左孩子为6 tree->insertAsRC(10); tree->left->insertAsLC(5); tree->left->insertAsRC(7); tree->right->insertAsLC(9); tree->right->insertAsRC(11); //输出当前二叉树 levels(tree); //Output: 8 7 10 5 6 9 11 std::cout << std::endl; //递归版二叉树的镜像 MirrorRecursively(tree); //输出镜像 levels(tree); //Output: 8, 10, 7, 11, 9, 6, 5 return 0;}
函数实现:
//递归版void MirrorRecursively(BinTreeNode *pNode){ if(pNode == NULL) return; //如果没有左孩子和右孩子也要return if(pNode->left == NULL && pNode->right == NULL) return; //否则交换左右孩子节点的值 //使用临时变量 BinTreeNode *temp = pNode->left; pNode->left = pNode->right; pNode->right = temp; //继续检查是否有非叶节点的左右子节点 if(pNode->left) MirrorRecursively(pNode->left); if(pNode->right) MirrorRecursively(pNode->right);}
其他函数实现:
//创建根节点,值为eBinTreeNode* BinTreeNode::createRoot(int e){ BinTreeNode *root = new BinTreeNode; root->m_value = e; return root; }//作为节点的左孩子插入元素evoid BinTreeNode::insertAsLC(int e){ BinTreeNode *Left = new BinTreeNode; Left->m_value = e; this->left = Left;}//作为节点的右孩子插入元素evoid BinTreeNode::insertAsRC(int e){ BinTreeNode *Right = new BinTreeNode; Right->m_value = e; this->right = Right;}//层次遍历,借助队列void levels(BinTreeNode *root){ if(root == NULL) return; std::queue<BinTreeNode*> Q; Q.push(root); while(!Q.empty()){//如果队列不为空 //赋值x,避免造成死循环 BinTreeNode *x = Q.front(); //先访问根节点(队首)的值 std::cout << x->m_value << " "; //访问后删除队首节点 Q.pop(); //如果有左孩子 if(x->left) Q.push(x->left);//入队 //如果有右孩子 if(x->right) Q.push(x->right);//入队 }}
0 0
- 二叉树的镜像20
- 二叉树的镜像
- 二叉树的镜像
- 二叉树的镜像
- 二叉树的镜像
- 二叉树的镜像
- 二叉树的镜像
- 二叉树的镜像
- 二叉树的镜像
- 二叉树的镜像
- 二叉树的镜像
- 二叉树的镜像
- 二叉树的镜像
- 二叉树的镜像
- 二叉树的镜像
- 二叉树的镜像
- 二叉树的镜像
- 二叉树的镜像
- 在一个字符串中找到第一个只出现一次的字符。
- socket与TCP/UDP编程
- PHP-超全局变量
- 说说Android的广播(2) - 并发队列和串行队列
- 【leetcode】230. Kth Smallest Element in a BST
- 二叉树的镜像20
- 十分钟搞定pandas
- Android Sqlite 数据库版本更新
- undefined reference to `png_create_write_struct'问题解决
- keras
- Android Intent调用大全、系统自带Intent调用大全
- Ubuntu wine / winetricks解决this msxml 6.0 is not supported on the current processor type
- 64位linux下eclipseADT不生成R.java文件的终极解决方案
- php调用接口的方法 curl