思路一(递归法)
使用递归。做递归题最重要的就是不要具体考虑怎么实现的,要从大的框架去理解。弄的递归函数的功能是什么,知道他是干什么的,用就行,还有就是寻找到终止条件。
代码
贴三个不同写法代码,越后面的代码是越开始写的。发现自己真的还有提高空间~
代码一
/**
* 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;
var left = mirrorTree(root.left);
var right = mirrorTree(root.right);
root.left = right;
root.right = left;
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 null;
var tree = new TreeNode(root.val);
tree.right = mirrorTree(root.left);
tree.left = mirrorTree(root.right);
return tree;
};
代码三
/**
* 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 && root.left == null && root.right == null) return new TreeNode(root.val);
if(!root) {
return root;
}else {
var tree = new TreeNode(root.val);
tree.right = mirrorTree(root.left);
tree.left = mirrorTree(root.right);
return tree;
}
};
思路二(辅助栈法)
思路参考自:剑指 Offer 27. 二叉树的镜像(递归 / 辅助栈,清晰图解)
利用栈(或队列)遍历树的所有节点 nodenode ,并交换每个 nodenode 的左 / 右子节点。
算法流程:
- 特例处理: 当 root为空时,直接返回 null;
- 初始化: 栈(或队列),本文用栈,并加入根节点 root。
- 循环交换: 当栈 stack为空时跳出;
- 出栈: 记为 node;添加子节点:将 node左和右子节点入栈;
- 交换: 交换 node的左 / 右子节点。
- 返回值:返回根节点 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 null;
var stack = [];
stack.push(root);
while(stack.length != 0) {
let node = stack.pop();
if(node.left) stack.push(node.left);
if(node.right) stack.push(node.right);
let temp;
temp = node.left;
node.left = node.right;
node.right = temp;
}
return root;
};