二叉树的镜像
来源:互联网 发布:医疗大数据工程师招聘 编辑:程序博客网 时间:2024/05/19 20:41
题目描述
操作给定的二叉树,将其变换为源二叉树的镜像。输入描述:
二叉树的镜像定义:源二叉树 8 / \ 6 10 / \ / \ 5 7 9 11 镜像二叉树 8 / \ 10 6 / \ / \ 11 9 7 5#include<iostream>#include<queue>using namespace std;struct TreeNode {int val;struct TreeNode *left;struct TreeNode *right;TreeNode(int x) :val(x), left(NULL), right(NULL) {}};class Solution {public: void Mirror(TreeNode *pRoot) { if(pRoot==NULL ||(pRoot->left==NULL&&pRoot->right==NULL)) return; TreeNode *ptemp; //交换左右孩子 ptemp=pRoot->left; pRoot->left=pRoot->right; pRoot->right=ptemp; if(pRoot->left) //结点没有左孩子时不进行递归,减少一次递归耗时 Mirror(pRoot->left); if(pRoot->right) //同上 Mirror(pRoot->right); }};/* 按层次顺序建立一棵二叉树 :队列 *//************************************************************/ TreeNode* LevelCreateBiTree(TreeNode* T){ TreeNode *p,*s;//p指向父亲结点,s指向孩子结点 queue<TreeNode*> BiNodeQueue;T=(TreeNode*)malloc(sizeof(TreeNode)); //生成根结点 int x; if(!(cin>>x)) return T; T->val=x; BiNodeQueue.push(T); //用队列实现层次遍历 while(!BiNodeQueue.empty()) { p=BiNodeQueue.front();BiNodeQueue.pop(); //为了简化操作,分别对左右子结点进行赋值。 if(cin>>x)//子树不空则进队列进行扩充。下同 { s=(TreeNode*)malloc(sizeof(TreeNode)); s->val=x; p->left=s; BiNodeQueue.push(s); } else { p->left=NULL; } if(cin>>x) { s=(TreeNode*)malloc(sizeof(TreeNode)); s->val=x; p->right=s; BiNodeQueue.push(s); } else { p->right=NULL; } } return T;}/*******************************************//* 按照层次遍历二叉树 *//*******************************************/void LevelOrderTraverse(TreeNode* T){ queue<TreeNode*> BiNodeQueue; TreeNode* p=T; BiNodeQueue.push(p); while(!BiNodeQueue.empty()) { p=BiNodeQueue.front();BiNodeQueue.pop(); if(p) { cout<<p->val<<" "; BiNodeQueue.push(p->left); BiNodeQueue.push(p->right); } }}void main(){TreeNode* T=NULL;T=LevelCreateBiTree(T);Solution text;text.Mirror(T);LevelOrderTraverse(T);}
阅读全文0 0
原创粉丝点击
热门IT博客
热门问题
老师的惩罚
人脸识别
我在镇武司摸鱼那些年
重生之率土为王
我在大康的咸鱼生活
盘龙之生命进化
天生仙种
凡人之先天五行
春回大明朝
姑娘不必设防,我是瞎子
学拼音韵母
前后鼻音韵母
双韵母有哪些
23个声母24个韵母
声母韵母整体音节
整体韵母
学习韵母
汉语拼音韵母
韵母学习
韵母有那些
韵母音节
单韵母双韵母
韵母多少个
韵母有多少个
音节韵母
韵母儿歌
韵母拼音
英语韵母
双韵母
韵母是什么
声母韵母复韵母
所有韵母
韵母声母表
26个韵母
什么叫韵母
学韵母
所有的韵母
韵母读法
哪些是韵母
韵母怎么写
小学韵母
二十四个韵母
特殊韵母有哪些
前韵母有哪些
声母韵母整体
韵母有哪几个
前鼻音韵母有几个
学习声母韵母
韵母有
韵母几个
韵母卡片