黄哥Python: Minimum Absolut Difference in BST 解题思路

154 阅读1分钟
原文链接: zhuanlan.zhihu.com

LeetCode 530.Minimum Absolute Difference in BST 解题思路。

Loading...leetcode.com图标

1、读题,Given a binary search tree with non-negative values, find the minimumabsolute differencebetween values of any two nodes.

节点的值都是non-negative , 求任意two nodes, 之间最小绝对值。

2、由于bst 特性,左子树的值小于根的值,右子树的值大于根的值。

bfs中序遍历,可以得到由小到大的一个list。

3、只有相邻的二个值,才会之差绝对值最小。那么求原来节点的问题,化解为list,前后二个元素之差最小的问题。

Python 代码

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
# 黄哥Python培训 黄哥所写
class Solution:
    def getMinimumDifference(self, root: TreeNode) -> int:
        if root is None:
            return 0
        nodes = []
        def bfs(root):
            if root is None:
                return
            bfs(root.left)
            nodes.append(root.val)
            bfs(root.right)
        bfs(root)
        minValue =  float("inf")
        if len(nodes) == 1:
            return nodes[0]
        diff_nodes = [nodes[i+1] - nodes[i] for i in range(len(nodes)) if i + 1 < len(nodes)]
        for item in diff_nodes:
            if item < minValue:
                minValue = item
        return minValue


还有一个奇葩的问题,783.Minimum Distance Between BST Nodes, 题的代码,和530题代码,

方法内部全部一样,都被AC

Loading...leetcode.com图标
黄哥:黄哥Python:提醒要转行当程序员的朋友,学习要分先后主次zhuanlan.zhihu.com图标黄哥:黄哥Python培训是这样训练学员的zhuanlan.zhihu.com图标