作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


题目地址: https://leetcode.com/problems/invert-binary-tree/

题目描述

Invert a binary tree.

Example:

Input:

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

Output:

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

Trivia:

This problem was inspired by this original tweet by Max Howell:

Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so f*** off.

题目大意

翻转二叉树。

解题方法

递归

这个题能够很好地帮助我们理解递归。

递归函数本身也是函数,调用递归函数就把它当做普通函数来看待,一定要只思考当前层的处理逻辑,明白该递归函数的输入输出是什么即可,调用的时候不要管函数内部实现。不要用肉脑 debug 递归函数的调用过程,会被绕进去。

首先来分析invertTree(TreeNode root)函数的定义:

  1. 函数的定义是什么?
    该函数可以翻转一棵二叉树,即将二叉树中的每个节点的左右孩子都进行互换。
  2. 函数的输入是什么?
    函数的输入是要被翻转的二叉树。
  3. 函数的输出是什么?
    返回的结果就是已经翻转后的二叉树。

然后我们来分析函数的写法:

  1. 递归终止的条件
    当要翻转的节点是空,停止翻转,返回空节点。
  2. 返回值
    虽然对 root 的左右子树都进行了翻转,但是翻转后的二叉树的根节点不变,故返回 root 节点。
  3. 函数内容
    root 节点的新的左子树:是翻转了的 root.right => 即 root.left = invert(root.right);
    root 节点的新的右子树:是翻转了的 root.left => 即 root.right = invert(root.left);

至此,递归函数就写完了。在『函数内容』编写的时候,是不是把递归函数invertTree(TreeNode root)当做了普通函数来用?调用invertTree(TreeNode root)函数就是能实现翻转二叉树的目的,不需要理解函数内部怎么实现的。

最后,提醒大家避免踩一个小坑,不能直接写成下面这样的代码:

root.left = invert(root.right)
root.right = invert(root.left)

这是因为第一行修改了root.left,会影响了第二行。在 Python 中,正确的写法是把两行写在同一行,就能保证 root.leftroot.right 的修改是同时进行的。

Python 解法如下:

# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None class Solution(object):
def invertTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if not root:
return
root.left, root.right = self.invertTree(root.right), self.invertTree(root.left)
return root

迭代

使用迭代方法。众所周知,把递归改成迭代需要一个栈,这个题使用迭代基本就是套个模板就好了,关键步骤只有一行,那就是把两个子树进行翻转。

# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None class Solution(object):
def invertTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
stack = []
stack.append(root)
while stack:
node = stack.pop()
if not node:
continue
node.left, node.right = node.right, node.left
stack.append(node.left)
stack.append(node.right)
return root

日期

2016/4/29 21:58:13
2018 年 10 月 8 日 —— 终于开学了。
2018 年 11 月 9 日 —— 睡眠可以

【LeetCode】226. Invert Binary Tree 翻转二叉树(Python)的更多相关文章

  1. leetcode 226 Invert Binary Tree 翻转二叉树

    大牛没有能做出来的题,我们要好好做一做 Invert a binary tree. 4 / \ 2 7 / \ / \ 1 3 6 9 to 4 / \ 7 2 / \ / \ 9 6 3 1 Tri ...

  2. 226. Invert Binary Tree 翻转二叉树

    [抄题]: Invert a binary tree. 4 / \ 2 7 / \ / \ 1 3 6 9 to 4 / \ 7 2 / \ / \ 9 6 3 1 [暴力解法]: 时间分析: 空间分 ...

  3. [LintCode] Invert Binary Tree 翻转二叉树

    Given n points on a 2D plane, find the maximum number of points that lie on the same straight line. ...

  4. Leetcode 226 Invert Binary Tree python

    题目: Invert a binary tree. 翻转二叉树. 递归,每次对节点的左右节点调用invertTree函数,直到叶节点. python中也没有swap函数,当然你可以写一个,不过pyth ...

  5. [LeetCode] Invert Binary Tree 翻转二叉树

    Invert a binary tree. 4 / \ 2 7 / \ / \ 1 3 6 9 to 4 / \ 7 2 / \ / \ 9 6 3 1 Trivia: This problem wa ...

  6. LeetCode 226. Invert Binary Tree (反转二叉树)

    Invert a binary tree. 4 / \ 2 7 / \ / \ 1 3 6 9 to 4 / \ 7 2 / \ / \ 9 6 3 1 Trivia:This problem was ...

  7. LeetCode 226 Invert Binary Tree(转换二叉树)

    翻译 将下图中上面的二叉树转换为以下的形式.详细为每一个左孩子节点和右孩子节点互换位置. 原文 如上图 分析 每次关于树的题目出错都在于边界条件上--所以这次细致多想了一遍: void swapNod ...

  8. Leetcode 226 Invert Binary Tree 二叉树

    交换左右叶子节点 /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * ...

  9. lintcode :Invert Binary Tree 翻转二叉树

    题目: 翻转二叉树 翻转一棵二叉树 样例 1 1 / \ / \ 2 3 => 3 2 / \ 4 4 挑战 递归固然可行,能否写个非递归的? 解题: 递归比较简单,非递归待补充 Java程序: ...

随机推荐

  1. Matlab指针数组

    Matlab指针数组 前面博客Matlab指针中介绍了如何在Matlab中使用handle类型对象作为指针使用,本文则介绍一些使用这些类型指针的小技巧. 自定义类型的指针数组 在大部分编程语言中,我们 ...

  2. Neville 插值方法

    简介 wikipedia: Neville's method 在数学上,Neville 算法是一种计算插值多项式方法,由数学家Eric Harold Neville提出.由给定的n+1个节点,存在一个 ...

  3. Matlab流体后处理中的奇淫巧术总结

    Matlab流体后处理中的奇淫巧术总结 主要参考\demos\volvec.m示例 1.等值面绘制 %% Isosurface of MRI Data cla load mri D = squeeze ...

  4. Linux—yum的python版本错误——高级解决方案

    彻底搞明白,python升级后,为什么会导致yum不可用 首先我们来分析下,python升级后,yum为什么会不可用? 先说个关于python的问题,Linux系统很多软件都依赖于python,因此不 ...

  5. Linux-centos7设置静态IP地址

    参考:https://blog.csdn.net/sjhuangx/article/details/79618865

  6. 14 - springboot的@Configuration、@Bean、@Import()、@ImportResource()、@Conditional说明

    1.@Configuration.@Bean.@Import().@ImportResource().@Conditional 分析源码的时候总会见到标题中的这几个注解,因此:弄一篇博客来说明一下吧, ...

  7. javaWeb - 2 — ajax、json — 最后附:后台获取前端中的input type = "file"中的信息 — 更新完毕

    1.ajax是什么? 面向百度百科一下就知道了,这里就简单提炼一下 Ajax即Asynchronous Javascript And XML(异步JavaScript和XML).当然其实我们学的应该叫 ...

  8. 用户体验再升级!Erda 1.2 版本正式发布

    来源|尔达 Erda 公众号 Erda v1.2 Changelog: https://github.com/erda-project/erda/blob/master/CHANGELOG/CHANG ...

  9. 大数据学习day31------spark11-------1. Redis的安装和启动,2 redis客户端 3.Redis的数据类型 4. kafka(安装和常用命令)5.kafka java客户端

    1. Redis Redis是目前一个非常优秀的key-value存储系统(内存的NoSQL数据库).和Memcached类似,它支持存储的value类型相对更多,包括string(字符串).list ...

  10. d3基础入门一-选集、数据绑定等核心概念

    引入D3 D3下载,本文下载时的版本为6.5.0 mkdir d3.6.5.0 unzip --help unzip d3.zip -d d3.6.5.0/ ls d3.6.5.0/ API.md C ...