剑指 Offer 27. 二叉树的镜像
题目描述
请完成一个函数,输入一个二叉树,该函数输出它的镜像。
例如输入:
镜像输出:
示例 1:
输入:root = [4,2,7,1,3,6,9]
输出:[4,7,2,9,6,3,1]
限制:
0 <= 节点个数 <= 1000
思路
- 用一个模拟队列访问到树的每一节点
- 自定义一个交换函数 swap
let swap = function(node){
[node.left, node.right] = [node.right, node.left];
}
- 边搜索边交换
代码
/**
* 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) {
//交换左右节点
let swap = function(node){
[node.left, node.right] = [node.right, node.left];
}
if(!root) return root;
let queue = [root];
while(queue.length){
let node = queue.shift();
swap(node);
if(node.left){
queue.push(node.left);
}
if(node.right){
queue.push(node.right);
}
}
return root;
};
其实 直接用递归更快 更好
递归代码
(此解法不是笔者原创 源于网络解法 提交代码后在执行用时分布图表中看到的 范例 无法提供链接)
/**
* 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 root;
//左右节点交换 一直递归到最后
let temp = root.left;
root.left = mirrorTree(root.right);
root.right = mirrorTree(temp);
return root;
};