【LeetCode】剑指 Offer 27. 二叉树的镜像 – Go 语言题解

导读:本篇文章讲解 【LeetCode】剑指 Offer 27. 二叉树的镜像 – Go 语言题解,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com


一、题目描述

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

例如输入:

     4
   /   \
  2     7
 / \   / \
1   3 6   9

镜像输出:

     4
   /   \
  7     2
 / \   / \
9   6 3   1

示例 1:

输入:root = [4,2,7,1,3,6,9]
输出:[4,7,2,9,6,3,1]

限制:

0 <= 节点个数 <= 1000


二、我的题解 – 递归

从根节点起,从顶至底,交换每个节点的左右孩子,直到越过叶子节点。

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func mirrorTree(root *TreeNode) *TreeNode {
    if root == nil{
        return nil
    }else{
        return symm(root)
    }
}

func symm(root *TreeNode) *TreeNode{
    var temp1,temp2 *TreeNode
    if root == nil{
        return nil
    }else if root.Left == nil && root.Right == nil {
        return root
    }else{
        temp1 = symm(root.Left)
        temp2 = symm(root.Right)
        root.Left = temp2
        root.Right = temp1
        return root
    }

}

评判结果:
在这里插入图片描述

实际上,你会发现上述代码是有重复部分的,可以改进:

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func mirrorTree(root *TreeNode) *TreeNode {
    var temp1,temp2 *TreeNode
    if root == nil{
        return nil
    }else if root.Left == nil && root.Right == nil {
        return root
    }else{
        temp1 = mirrorTree(root.Left)
        temp2 = mirrorTree(root.Right)
        root.Left = temp2
        root.Right = temp1
        return root
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/118968.html

(0)
seven_的头像seven_bm

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!