来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/er-cha-shu-de-jing-xiang-lcof 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
请完成一个函数,输入一个二叉树,该函数输出它的镜像。
解答
递归替换左右节点即可,但是注意可优化性能的点是,少使用一个函数:
/*** Definition for a binary tree node.* function TreeNode(val) {* this.val = val;* this.left = this.right = null;* }*//*** @param {TreeNode} root* @return {TreeNode}*/var mirrorTree = function(root) {if (!root) return null;let left = root.left;root.left = root.right;root.right = left;mirrorTree(root.left);mirrorTree(root.right);};
直接使用 mirrorTree,而非再声明个 traverse,速度要快很多
