题目描述
- 感觉和合并二叉树类似,都是很好进行递归的问题
代码 & 思路
- 翻转当前结点的左、右结点
- 对当前结点的左、右结点进行翻转函数
- 【自底向上】
class Solution {
TreeNode left;
public TreeNode invertTree(TreeNode root) {
if(root == null){
return root;
}
invertTree(root.left);
invertTree(root.right);
left = root.left;
root.left = root.right;
root.right = left;
return root;
}
}
更新版
class Solution {
public TreeNode invertTree(TreeNode root) {
if(root == null) {
return null;
}
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
invertTree(root.left);
invertTree(root.right);
return root;
}
}
class Solution {
public TreeNode mirrorTree(TreeNode root) {
if(root == null) return null;
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
mirrorTree(root.left);
mirrorTree(root.right);
return root;
}
}