题目在这里,要求一个二叉树的倒数第二个小的值。二叉树的特点是父节点的值会小于子节点的值,父节点要么没有子节点,要不左右孩子节点都有。

分析一下,根据定义,跟节点的值肯定是二叉树中最小的值,剩下的只需要找到左右子树中比跟节点大的最小值就可以了。对于这个题目,还是考察的二叉树的搜索,第一印象是BFS。使用一个辅助队列存储遍历过程中的节点,遍历过程中,如果节点的值比结果中第二小的值还大,就不用继续把该节点及其所有的子节点入队了,这样可以节省时间。这里的辅助队列使用的是deque,在两端存取数据的复杂度都是O(1),List取出第一个元素的复杂度是O(n)。代码如下:

 # 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 findSecondMinimumValue(self, root):
"""
:type root: TreeNode
:rtype: int
"""
from collections import deque
if not root:
return -1
stack = deque([root])
ret = [root.val]
while stack:
node = stack.popleft()
if node:
if node.val > ret[-1]:
if len(ret) < 2:
ret.append(node.val)
else:
if ret[0] < node.val < ret[1]:
ret[1] = node.val
stack.append(node.left)
stack.append(node.right)
return ret[1] if len(ret) == 2 else -1

每次做完都要去讨论区看看有没有亮瞎眼的解法,把DFS的代码贴在下面,思路是一样的,不过看着更简洁了:

 class Solution(object):
def findSecondMinimumValue(self, root):
"""
:type root: TreeNode
:rtype: int
"""
# Time: O(n)
# Space: O(lgn)
res = [float('inf')]
def traverse(node):
if not node:
return
if root.val < node.val < res[0]:
res[0] = node.val
traverse(node.left)
traverse(node.right)
traverse(root)
return -1 if res[0] == float('inf') else res[0]

这里需要说一下代码中的float('inf'),以前倒是真没用到这里,这是Python中代表正无穷的写法,负无穷就是float('-inf')了,又了解了一个新内容,嘿嘿。

Python 解LeetCode:671. Second Minimum Node In a Binary Tree的更多相关文章

  1. LeetCode 671. Second Minimum Node In a Binary Tree

    Given a non-empty special binary tree consisting of nodes with the non-negative value, where each no ...

  2. LeetCode 671. Second Minimum Node In a Binary Tree二叉树中第二小的节点 (C++)

    题目: Given a non-empty special binary tree consisting of nodes with the non-negative value, where eac ...

  3. 【Leetcode_easy】671. Second Minimum Node In a Binary Tree

    problem 671. Second Minimum Node In a Binary Tree 参考 1. Leetcode_easy_671. Second Minimum Node In a ...

  4. 【LeetCode】671. Second Minimum Node In a Binary Tree 解题报告(Python)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 找出所有值再求次小值 遍历时求次小值 日期 题目地址 ...

  5. [LeetCode&Python] Problem 671. Second Minimum Node In a Binary Tree

    Given a non-empty special binary tree consisting of nodes with the non-negative value, where each no ...

  6. 【easy】671. Second Minimum Node In a Binary Tree

    Given a non-empty special binary tree consisting of nodes with the non-negative value, where each no ...

  7. 671. Second Minimum Node In a Binary Tree 非递减二叉树中第二小的元素

    [抄题]: Given a non-empty special binary tree consisting of nodes with the non-negative value, where e ...

  8. 671. Second Minimum Node In a Binary Tree

    /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode ...

  9. LeetCode 671. 二叉树中第二小的节点(Second Minimum Node In a Binary Tree) 9

    671. 二叉树中第二小的节点 671. Second Minimum Node In a Binary Tree 题目描述 给定一个非空特殊的二叉树,每个节点都是正数,并且每个节点的子节点数量只能为 ...

随机推荐

  1. Nim or not Nim? hdu3032 SG值打表找规律

    Nim or not Nim? Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)T ...

  2. Canal 同步异常分析:Could not find first log file name in binary log index file

    文章首发于[博客园-陈树义],点击跳转到原文Canal同步异常分析:Could not find first log file name in binary log index file. 公司搜索相 ...

  3. 项目发布Debug和Release版的区别

    一.Debug和Release的区别 Debug:调试版本,包含调试信息,所以容量比Release大很多,并且不进行任何优化(优化会使调试复杂化,因为源代码和生成的指令间关系会更复杂),便于程序员调试 ...

  4. 浅谈Spring的AOP实现-动态代理

    说起Spring的AOP(Aspect-Oriented Programming)面向切面编程大家都很熟悉(Spring不是这次博文的重点),但是我先提出几个问题,看看同学们是否了解,如果了解的话可以 ...

  5. 如何在Windows系统中配置Mysql群集(Mysql Cluster)

    MySQL群集技术在分布式系统中为MySQL数据提供了冗余特性,增强了安全性,使得单个MySQL服务器故障不会对系统产生巨大的负面效应,系统的稳定性得到保障. Mysql群集(Cluster)简介 M ...

  6. 浅谈Java抽象类

    什么是抽象类?这名字听着就挺抽象的,第一次听到这个名字还真有可能被唬住.但是,就像老人家所说的,一切反动派都是纸老虎,一切有着装x名字的概念也是纸老虎.好吧,我们已经从战略上做到了藐视它,现在就要战术 ...

  7. JAVA中子类会不会继承父类的构造方法

    声明:刚刚接触java不久,如果理解有错误或偏差望各位大佬强势批判 java中子类能继承父类的构造方法吗? 父类代码: class Father { String name ; //就不set/get ...

  8. [js插件开发教程]原生js仿jquery架构扩展开发选项卡插件

    jquery插件一般是这么干的: $.fn.插件名称 = function(){}, 把插件的名称加在.fn上,在源码里面实际上是扩展到构造函数的原型对象上,如果你没看过jquery的源代码,或者你曾 ...

  9. win10 uwp 绑定多数据

    经常我们需要绑定的数据有多个,当添加到集合控件的对象类型结构比较复杂,我们希望自己来定义排版布局,这时可以使用ItemTemplate用资源的定义 现在有数据 public class caddres ...

  10. win10 sdk 是否向下兼容

    向下兼容(downward compatibility),又称向后兼容(backward compatibility).回溯兼容,在计算机中指在一个程序.库或硬件更新到较新版本后,用旧版本程序创建的文 ...