题目描述
操作给定的二叉树,将其变换为源二叉树的镜像。
输入描述:
解题思路
题意就是 交换二叉树中每个结点的两个子女
1. 递归实现
- 先交换先交换左右孩子的左右子树
- 再交换左右孩子
该解法见C++代码
2. 非递归实现
采用广度遍历算法 + 队列实现(深度遍历也可)
- 将根节点入队
- 取出根结点并交换根节点的左右孩子
- 左右孩子已被交换完毕,将其依次入队
- 取出队头结点并交换该结点的左右孩子
- 左右孩子已被交换完毕,将其依次入队
- 依次类推,直到队空。。。
该解法见Java代码
具体代码
- C++ 递归实现
/*
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 *root) {
if(root != NULL){
Mirror(root->left);
Mirror(root->right);
TreeNode *temp = root->left;
root->left = root->right;
root->right = temp;
}
}
};
- Java 非递归实现
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
import java.util.LinkedList;
import java.util.Queue;
public class Solution {
public void Mirror(TreeNode root) {
if(root == null)
return ;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root); //根节点入队
while(!queue.isEmpty()){
// 队列非空
int len = queue.size();
for(int i = 0;i<len;i++){
TreeNode curr = queue.poll(); //取出队头
//交换该结点的左右孩子
TreeNode temp = curr.left;
curr.left = curr.right;
curr.right = temp;
if(curr.left != null) //若该节点有左孩子,则将其入队,等待交换
queue.offer(curr.left);
if(curr.right != null)
queue.offer(curr.right); //若该节点有右孩子,则将其入队,等待交换
}
}
}
}
👉 👉 👉 原文首发 - 小牛肉的个人博客,欢迎来访~👈 👈 👈