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

Example:
Input:

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.
This question is the same as 783: https://leetcode.com/problems/minimum-distance-between-bst-nodes/

Solution in python:

# 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:
        result = []
        def traverse(root):
            if root == None:
                return 
            else:
                traverse(root.left)
                result.append(root.val)
                traverse(root.right)
        traverse(root)
        first = result[0]
        min_dif = float("inf")
        for i in range(1,len(result)):
            difference = result[i] - first
            if difference < min_dif:
                min_dif = difference
            first = result[i]
        return min_dif
最后修改日期: 2021年2月1日

留言

撰写回覆或留言

发布留言必须填写的电子邮件地址不会公开。