作者: 负雪明烛
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. 毕业设计之zabbix+微信企业号报警

    需要自己申请一个微信企业号 创建应用 AgentId 1000003 Secret SOI8b20G96yUVM29K02-bP5N5o6dovwSF2RrDaXHJNg 企业ID(自己再企业信息里面 ...

  2. 问题记录:SNP 标记 phasing

    GATK4 检测的SNP标记,有些位点会在检测过程中完成 phasing,在后续做基因型填充的时候有坑. GATK4 phasing 结果的缺失位点不是 ./. 也不是 .|.  而是直接变成一个单独 ...

  3. echo 输出彩色字符

    借助echo的-e选项来实现,语法格式为 echo -e "\033[3xmsome things you want to print out.\033[0m" \033[3xm为 ...

  4. mysql—MySQL数据库中10位或13位时间戳和标准时间相互转换

    1.字符串时间转10位时间戳 select FLOOR(unix_timestamp(create_time)) from page; #create_time为字段名 page为表名 eg:sele ...

  5. gcc 的编译流程 和gdb的调试方法

    GCC的编译流程分为四个步骤: 预处理(Pre-Processing) 编译(Compiling) 汇编(Assembling) 链接(Linking) 可以看的出来文件大小 gdb 调试 gdb - ...

  6. 小程序https启用tls1.2

    公司的web服务器是iis7,在开发微信小程序的时候,需要启用TLS1.2. 将下面的代码复制到文本,存为reg文档,双击搞定. Windows Registry Editor Version 5.0 ...

  7. Vulnstack内网靶场5

    实验环境搭建 漏洞详情 (qiyuanxuetang.net) "此次靶场虚拟机共用两个,一个外网一个内网,用来练习红队相关内容和方向,主要包括常规信息收集.Web攻防.代码审计.漏洞利用. ...

  8. 微信小程序扫描普通二维码打开小程序的方法

    很久没有写博客了,之前换了一份工作,很久没有做Android开发了,现在转做前端开发了,记录一下遇到的问题及解决的方法. 最近做微信小程序开发,遇到一个需求,后台管理系统生成的问卷和投票会有一个二维码 ...

  9. 脱离Editor、VS等IDE如何编译UE4工程

    在Windows平台下,我们从.uproject文件生成VS解决方案.sln文件 .uproject文件用于打开Editor .sln文件用于打开VS工程 对于有增加C++代码的工程,Editor中和 ...

  10. Redis | 第10章 二进制数组、慢查询日志和监视器《Redis设计与实现》

    目录 前言 1. 二进制位数组 1.1 位数组的表示 1.2 GETBIT 命令的实现 1.3 SETBIT 命令的实现 1.4 BITECOUNT 命令的实现 1.5 BITOP 命令的实现 2. ...