本质还是节点的左节点和右节点的交换

    • 通过递归交换节点的左右节点
    • 通过层级遍历然后交换左右节点
      1. //递归写法
      2. function mirrorTree(root){
      3. //递归结束条件
      4. if(root){
      5. [root.left,root.right] = [root.right,root.left];
      6. mirrorTree(root.left);
      7. mirrorTree(root.right);
      8. }
      9. return root;
      10. }
      function mirrorTree(root) {
        //用个栈维护迭代
        let stack = [];
        stack.push(root);
        while (stack.length > 0) {
            let node = stack.pop();
            if (node == null) continue;//为什么不是val,因为如果是叶子节点,直接就是null,非null的都是对象
            //本质交换
            [node.left, node.right] = [node.right, node.left];
            //左右子节点继续压入栈
            stack.push(node.left);
            stack.push(node.right);
        }
        //返回结果
        return root;
      }