操作给定的二叉树,将其变换为源二叉树的镜像。
题目抽象:给定一颗二叉树,将二叉树的左右孩子进行翻转,左右孩子的子树做相同的操作。
方法一:递归(dfs)
代码
class Solution {
public:
TreeNode* dfs(TreeNode *r) {
if (!r) return nullptr;
TreeNode *lval = dfs(r->left);
TreeNode *rval = dfs(r->right);
r->left = rval, r->right = lval;
return r;
}
void Mirror(TreeNode *pRoot) {
if (!pRoot) return;
dfs(pRoot);
}
};
时间复杂度:O(n),n为树节点的个数。每个节点只用遍历一次,所以为O(n)
空间复杂度:O(n), 每个节点都会在递归栈中存一次
方法二:层次遍历(bfs)
class Solution {
public:
void Mirror(TreeNode *pRoot) {
if(!pRoot){
return;
}
queue<TreeNode*> res;//借助队列实现树的层次遍历
res.push(pRoot);
while(!res.empty()){//外层while循环处理总共多少层,队列不为空就继续循环
int sz=res.size();
while(sz--){//内层while循环处理每层结点
TreeNode* node=res.front();
res.pop();//得到队列首元素,然后首元素出队列
if(node->left) res.push(node->left);//顺序的将下层结点入队列
if(node->right) res.push(node->right);
//底下是解决我们的需求:当前结点的左右子节点进行交换
TreeNode* tmp=node->left;
node->left=node->right;
node->right=tmp;
}
}
}
};