来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/er-cha-shu-de-jing-xiang-lcof 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

请完成一个函数,输入一个二叉树,该函数输出它的镜像。

解答

递归替换左右节点即可,但是注意可优化性能的点是,少使用一个函数:

  1. /**
  2. * Definition for a binary tree node.
  3. * function TreeNode(val) {
  4. * this.val = val;
  5. * this.left = this.right = null;
  6. * }
  7. */
  8. /**
  9. * @param {TreeNode} root
  10. * @return {TreeNode}
  11. */
  12. var mirrorTree = function(root) {
  13. if (!root) return null;
  14. let left = root.left;
  15. root.left = root.right;
  16. root.right = left;
  17. mirrorTree(root.left);
  18. mirrorTree(root.right);
  19. };

直接使用 mirrorTree,而非再声明个 traverse,速度要快很多