Skip to content

Latest commit

 

History

History
46 lines (33 loc) · 921 Bytes

27. 二叉树的镜像.md

File metadata and controls

46 lines (33 loc) · 921 Bytes

题目链接:

剑指 Offer 27. 二叉树的镜像

思路:

  • 递归出口:当前节点为空,返回null
  • 递归中要做的事:交换左右节点
  • 将当前节点返回给上一级

代码:

JavaScript

写法1:

const mirrorTree = root => {
    // 递归出口
    if (!root) return null;
    // 交换当前左右节点
    [root.left, root.right] = [root.right, root.left];
    // 递归交换左子树的左右节点
    mirrorTree(root.left);
    // 递归交换右子树的左右节点
    mirrorTree(root.right);
    // 返回当前节点给上一级
    return root;
};

写法2:

const mirrorTree = root => {
  if (!root) return null;

  const node = new TreeNode(root.val);

  node.left = mirrorTree(root.right);
  node.right = mirrorTree(root.left);

  return node;
};