leetcode|一道算法题错失谷歌offer

1,239 阅读2分钟

今天是 Kevin 的算法之路的第 8 天。为大家讲解 LeetCode 第 226 题,是一道简单却让大佬 Max Howell(Homebrew 的开发者)错失谷歌的offer的题。让我们一起来了解一下吧~

每日一笑

小明:“我努力起来自己都怕。”

爸爸:“那你努力啊。”

小明:“可我怕啊。”

题目描述

翻转一棵二叉树。

示例:

输入:

   4

   /   \
  2     7
 / \   / \
1   3 6   9
输出:

   4

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

备注: 这个问题是受到 Max Howell 的 原问题 启发的 :

谷歌:我们90%的工程师使用您编写的软件(Homebrew),但是您却无法在面试时在白板上写出翻转二叉树这道题,这太糟糕了。

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/invert-binary-tree 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解题思路

因为树具有天然的递归结构,关于树的问题,我们常用递归来实现。

翻转二叉树,我们首先判断如果反转一颗空树结果还是一颗空树。

如果不是空树,就将父节点的左右节点交换,并进行递归。

代码实现

//go
/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func invertTree(root *TreeNode) *TreeNode {
    if root == nil {
        return nil
    }
    // tmp := root.Left
    // root.Left = root.Right
    // root.Right = tmp
    root.Left, root.Right = root.Right, root.Left // go语法交换元素,等价于上面3行代码
    root.Left = invertTree(root.Left) // 递归左子树
    root.Right = invertTree(root.Right) // 递归柚子树
    return root
}
//java
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode invertTree(TreeNode root) {
        if (root == null) {
            return null;
        }
        TreeNode tmp = root.left;
        root.left = root.right;
        root.right = tmp;
        root.right = invertTree(root.right);
        root.left = invertTree(root.left);
        return root;
    }
}

好了,这道题是不是很简单,学会了吧?!快去拿谷歌的offer吧!(当然你可能还差一个Homebrew😂)

郑重声明:

所展示代码已通过 LeetCode 运行通过,请放心食用~

在唠唠嗑

很多人都想养成好习惯,但大多数人却是三分钟热度。为了我们能一起坚持下去,决定制定如下计划(福利)

一起学算法,打卡领红包!

参与方式:

关注我的原创微信公众号「Kevin的学堂」,一起学习,一起更优秀!

打卡规则为:

「留言」“打卡XXX天” ➕「分享」到朋友圈

奖励:

连续打卡 21 天,联系本人获取 6.6 元红包一个!

连续打卡 52 天,联系本人获取 16.6 元红包一个!

连续打卡 100 天,联系本人获取 66.6 元红包一个!