zoukankan      html  css  js  c++  java
  • 530. Minimum Absolute Difference in BST

    Given a binary search tree with non-negative values, find the minimum absolute difference between values of any two nodes.

    Example:

    Input:

    1

    3
    /
    2

    Output:
    1

    Explanation:
    The minimum absolute difference is 1, which is the difference between 2 and 1 (or between 2 and 3).

    Note: There are at least two nodes in this BST.

    class Solution(object):
        def getMinimumDifference(self, root):
            """
            :type root: TreeNode
            :rtype: int
            """
            list = []
            def preorder(temp):
                if temp == None:
                    return
                list.append(temp.val)
                preorder(temp.left)
                preorder(temp.right)
            preorder(root)
            m = 9999999
            list.sort()
            for i in range(len(list)-1):
                m = min(list[i+1] - list[i],m)
            return m
    

    求的是任意两个节点之间的最小值,先序遍历把数组保存下来,排序之后遍历一遍。

  • 相关阅读:
    每周总结03
    Servlet2
    每周总结02
    周总结4
    河北省重大需求征集系统每日进度6
    周总结3
    hadoop命令
    复习uml
    周总结2
    河北省重大需求征集系统每日进度5
  • 原文地址:https://www.cnblogs.com/bernieloveslife/p/9707281.html
Copyright © 2011-2022 走看看