JavaScript题解 | #二叉树的镜像#
二叉树的镜像
https://www.nowcoder.com/practice/a9d0ecbacef9410ca97463e4a5c83be7
/*
 * function TreeNode(x) {
 *   this.val = x;
 *   this.left = null;
 *   this.right = null;
 * }
 */
/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param pRoot TreeNode类 
 * @return TreeNode类
 */
function Mirror( pRoot ) {
    if(!pRoot) return null;
    const temp = pRoot.left;
    pRoot.left = pRoot.right;
    pRoot.right = temp;
    pRoot.left && Mirror(pRoot.left);
    pRoot.right && Mirror(pRoot.right);
    return pRoot;
}
module.exports = {
    Mirror : Mirror
};
思路:
1、交换root的左右两个节点,这是镜像二叉树的本层操作。后续的递归就是对二叉树的每个节点都进行镜像操作
2、如果有左子树,就递归左子树的镜像 Mirror(root.left)
3、如果有右子树,就递归右子树的镜像 Mirror(root.right)
4、if root == null 返回 null

 
查看1道真题和解析