剑指 Offer 27. 二叉树的镜像

思路一(递归法)

使用递归。做递归题最重要的就是不要具体考虑怎么实现的,要从大的框架去理解。弄的递归函数的功能是什么,知道他是干什么的,用就行,还有就是寻找到终止条件。

代码

贴三个不同写法代码,越后面的代码是越开始写的。发现自己真的还有提高空间~
代码一

/**
 * 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 的左 / 右子节点。
算法流程:

  1. 特例处理: 当 root为空时,直接返回 null;
  2. 初始化: 栈(或队列),本文用栈,并加入根节点 root。
  3. 循环交换: 当栈 stack为空时跳出;
    • 出栈: 记为 node;添加子节点:将 node左和右子节点入栈;
    • 交换: 交换 node的左 / 右子节点。
  4. 返回值:返回根节点 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;
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值