Skip to content

530. Minimum Absolute Difference in BST

题目

Given the root of a Binary Search Tree (BST), return the minimum absolute difference between the values of any two different nodes in the tree.

 

Example 1:

Input: root = [4,2,6,1,3]
Output: 1

Example 2:

Input: root = [1,0,48,null,null,12,49]
Output: 1

 

Constraints:

  • The number of nodes in the tree is in the range [2, 104].
  • 0 <= Node.val <= 105

 

Note: This question is the same as 783: https://leetcode.com/problems/minimum-distance-between-bst-nodes/

Related Topics
  • 深度优先搜索
  • 广度优先搜索
  • 二叉搜索树
  • 二叉树

  • 👍 627
  • 👎 0
  • 思路

    BST 中序列遍历即可得到一个从 asc 的队列,比较 asc 队列的前后差值即可找到最小值

    解法

    py
    # leetcode submit region begin(Prohibit modification and deletion)
    # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, val=0, left=None, right=None):
    #         self.val = val
    #         self.left = left
    #         self.right = right
    class Solution:
        def getMinimumDifference(self, root: Optional[TreeNode]) -> int:
            self.res = float('inf')
            self.pre = None
            def dfs(node: Optional[TreeNode]):
                if not node:
                    return
    
                dfs(node.left)
                if self.pre is not None:
                    self.res = min(self.res, abs(node.val - self.pre))
                self.pre = node.val
                dfs(node.right)
    
    
            dfs(root)
            return self.res
    
            
    # leetcode submit region end(Prohibit modification and deletion)

    复杂度分析

    • 时间复杂度 O(N)
    • 空间复杂度 O(N)