1. 考察知识点
- 二叉树、递归
2. 题目
- 操作给定的二叉树,将其变换为源二叉树的镜像。
3. 思路
其实就是对每个左右子节点进行交换
4. 代码实现
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public void Mirror(TreeNode root) {
//如果二叉树没有节点或者只有一个根节点,则不需要做镜像
if (root == null || (root.left == null && root.right == null)) {
return;
}
// 反转当前节点的左右子节点
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
//判断该左右节点下有没有子节点,如果有继续反转
if (root.left != null){
Mirror(root.left);
}
if (root.right != null){
Mirror(root.right);
}
}
}