作者: 负雪明烛
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. Requests的安装和使用

    一.Requests的安装1.pip3 install requests2.验证 import requests 不报错即可

  2. 字符串String的trim()方法

    用来删除字符串两端的空白字符并返回,trim方法并不影响原来的字符串本身,它返回的是一个新的字符串 String a = "  Hello World  "; String b = ...

  3. 用JS实现方块碰撞

    首先我们应用上次的内容--方块拖拽,利用方块拖拽来让两个方块进行碰撞. 我们可以先定义两个正方形方块,红色的div1,绿色的div2,我们来实现当div1碰撞div2时div2的颜色变为黄色 HTML ...

  4. Redis | 第11章 服务器的复制《Redis设计与实现》

    目录 前言 1. 旧版复制功能的实现 1.1 同步与命令传播 1.2 旧版复制功能的缺陷 2. 新版复制功能的实现 2.1 部分重同步的实现原理 3. PSYNC 命令的实现 4. 复制的详细步骤 4 ...

  5. 用python写的推箱子搜索程序

    1 # -*- coding: gbk -*- 2 from functools import reduce 3 from copy import deepcopy 4 import re 5 def ...

  6. Elasticsearch【基础入门】

    目录 一.操作index 1.查看index 2.增加index 3.删除index 二.操作index 1.新增document 2.查询type 全部数据 3.查找指定 id 的 document ...

  7. 单体内置对象 Global 和 Math

    单体内置对象 Global 和 Math 在所有代码执行前,作用域中就已经存在两个内置对象:Global(全局)和Math.在大多数ES实现中都不能直接访问Global对象.不过,WEB浏览器实现了承 ...

  8. 案例 stm32的dma传输过程

    首先说一下:DMA_GetCurrDataCounter返回值是什么 返回值是dma缓存里还剩余多少空间. 上面本来应该是,发一下,改变一下.但是这里有一行是特殊的. long : 461,*ff l ...

  9. Oracle trunc和round的区别

    1.关于trunc 和round函数比较 整体概括: round函数 四舍五入trunc函数 直接截取 对于时间: Round函数对日期进行"四舍五入",Trunc函数对日期进行截 ...

  10. 【Matlab】快速傅里叶变换/ FFT/ fftshift/ fftshift(fft(fftshift(s)))

    [自我理解] fft:可以指定点数的快速傅里叶变换 fftshift:将零频点移到频谱的中间 用法: Y=fftshift(X) Y=fftshift(X,dim) 描述:fftshift移动零频点到 ...