26.二叉树的镜像
小于 1 分钟
26.二叉树的镜像
参考链接
个人尝试
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode mirrorTree(TreeNode root) {
//递归
//新建tmp,交换左右子树,左右子树的子树交换,划分为一样的子问题
//递归结束条件
if (root == null) return root;
TreeNode tmp = root.left;
root.left = root.right;
root.right = tmp;
if (root.left != null) mirrorTree(root.left);
if (root.right != null) mirrorTree(root.right);
return root;
}
}
优秀题解
class Solution {
public TreeNode mirrorTree(TreeNode root) {
if(root == null) return null;
TreeNode tmp = root.left;
root.left = mirrorTree(root.right);
root.right = mirrorTree(tmp);
return root;
}
}
作者:Krahets
链接:https://leetcode.cn/problems/er-cha-shu-de-jing-xiang-lcof/solutions/180718/mian-shi-ti-27-er-cha-shu-de-jing-xiang-di-gui-fu-/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
差异:
个人尝试 先交换,再翻转左右子树
优秀题解 直接翻转子树,随后将返回的子树交换