leetcode530 -- Minimum Absolute Difference in BST.

leetcode530 -- 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).

这个题还之前的那个可以用完全一样的代码来做,不过中序遍历得到排好序的数组只是一种办法。

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def getMinimumDifference(self, root: TreeNode) -> int:
        
        res = []
        if not root:
            return 
        
        self.inorder(root, res)
        mini = float('inf')
        for i in range(len(res)-1):
            mini = min(mini, res[i+1]-res[i])
            
        return mini
        
    def inorder(self, root, res):
        if not root:
            return 
        
        self.inorder(root.left, res)
        res.append(root.val)
        self.inorder(root.right, res)

打赏,谢谢~~

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,多谢支持~

打开微信扫一扫,即可进行扫码打赏哦