JZ18_二叉树的镜像
知识点:二叉树
题目链接
题目描述
操作给定的二叉树,将其变换为源二叉树的镜像。
比如: 源二叉树
8
/ \
6 10
/ \ / \
5 7 9 11
镜像二叉树
8
/ \
10 6
/ \ / \
11 9 7 5
示例1
输入: {8,6,10,5,7,9,11}
返回值: {8,10,6,11,9,7,5}
解题思路
- 递归返回的条件:结点是空的
- 遍历树的结点呢,可以采用二叉树的前序遍历方式
void preOrder(TreeNode *r) { if (!r) return; // process r preOrder(r->left); preOrder(r->right); }
- 进行操作,左右交换结点
代码
class Solution {
public:
TreeNode* Mirror(TreeNode* pRoot) {
if(pRoot == nullptr)
return pRoot;
swap(pRoot->left,pRoot->right);
Mirror(pRoot->left);
Mirror(pRoot->right);
return pRoot;
}
};
class Solution {
public:
void Mirror(TreeNode *pRoot) {
queue<TreeNode*> pq;
pq.push(pRoot);
while (!pq.empty()) {
int sz = pq.size();
while (sz--) {
TreeNode *node = pq.front();
pq.pop();
if (node->left) pq.push(node->left);
if (node->right) pq.push(node->right);
TreeNode *cur = node->left;
node->left = node->right;
node->right = cur;
}
}
}
};
今天也是爱zz的一天!