- 递归出口:当前节点为空,返回
null
- 递归中要做的事:交换左右节点
- 将当前节点返回给上一级
写法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;
};