18、二叉树的镜像 可以再过一遍
操作给定的二叉树,将其变换为源二叉树的镜像。
输入描述:
二叉树的镜像定义:源二叉树
8
/ \
6 10
/ \ / \
5 7 9 11
镜像二叉树
8
/ \
10 6
/ \ / \
1、借助队列来做,跟上面一题中的迭代版本很像
void Mirror(TreeNode* pRoot) {
if (pRoot == nullptr) return;
queue<TreeNode*> q;
q.push(pRoot);
while (!q.empty()) {
TreeNode* node = q.front();
q.pop();
if (node)
{
q.push(node->left);
q.push(node->right);
swap(node->left, node->right);
}
}
}
2、不使用swap函数的迭代版本
void Mirror(TreeNode* pRoot) {
if (pRoot == nullptr) return;
queue<TreeNode*> q;
q.push(pRoot);
while (!q.empty()) {
TreeNode* node = q.front();
q.pop();
if (node)
{
q.push(node->left);
q.push(node->right);
//swap(node->left, node->right);
TreeNode* temp = node->left;
node->left = node->right;
node->right = temp;
}
}
}
3、递归版本
void Mirror(TreeNode *pRoot) {
if (pRoot == nullptr) return;
TreeNode* temp = pRoot->left;
pRoot->left = pRoot->right;
pRoot->right = temp;
Mirror(pRoot->right);
Mirror(pRoot->left);
}
4、栈的迭代版本
void Mirror(TreeNode* pRoot) {
if (pRoot == nullptr) return;
stack<TreeNode*> s;
s.push(pRoot);
while (!s.empty()) {
TreeNode* node = s.top();
s.pop();
if (node) {
s.push(node->left);
s.push(node->right);
swap(node->left, node->right);
}
}
}
二刷:
1、迭代版本,想多了
运行时间:2ms 占用内存:376k
队列来做,有点类似于层次遍历的意思
void Mirror(TreeNode *pRoot) {//有点类似于二叉树的层次遍历
if(pRoot == nullptr) return;
queue<TreeNode*> q;
TreeNode *node = nullptr;
q.push(pRoot);
while(!q.empty()){
node = q.front();
q.pop();
if(node != nullptr)
{ q.push(node->left);
q.push(node->right);
swap(node->left,node->right);
}
}
}
2、递归版本,而更容易理解一些,也更好写
运行时间:2ms 占用内存:504k
void Mirror(TreeNode *pRoot) {//有点类似于二叉树的层次遍历
if(pRoot == nullptr) return;
swap(pRoot->left,pRoot->right);
Mirror(pRoot->left);
Mirror(pRoot->right);
}
美女帅哥们如果觉得写的还行,有点用的话麻烦点个赞或者留个言支持一下阿秀~
如果觉得狗屁不通,直接留言开喷就完事了。