【中等】二叉树的镜像- 2.27

75 阅读1分钟

题目链接:

题解:

/*
 * function TreeNode(x) {
 *   this.val = x;
 *   this.left = null;
 *   this.right = null;
 * }
 */
/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param pRoot TreeNode类 
 * @return TreeNode类
 */
function Mirror( pRoot ) {
    // write code here
    if (!pRoot) return null
    const left = Mirror(pRoot.left)
    const right = Mirror(pRoot.right)
    pRoot.left = right
    pRoot.right = left
    return pRoot
}

总结:

  1. 递归记录左右子树,之后交换即可