描述
Given a binary search tree with non-negative values, find the minimum absolute difference between values of any two nodes.
Example 1:
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.
This question is the same as 783: https://leetcode.com/problems/minimum-distance-between-bst-nodes/
解析
根据题意,就是找出任意两个节点的值的最小值。解决思路也比较简单,用中序遍历将所有的值放入列表中,然后按顺序遍历列表计算出最小差值即可。可以优化的思路是将最后遍历计算最小差值的步骤就放入递归里面,在递归的时候就顺便计算了。
解答
class Solution(object):
def getMinimumDifference(self, root):
"""
:type root: TreeNode
:rtype: int
"""
self.result = float("inf")
self.nodes = []
def inOrder(root):
if not root: return
inOrder(root.left)
self.nodes.append(root.val)
inOrder(root.right)
inOrder(root)
for i in range(1, len(self.nodes)):
self.result = min(self.result, self.nodes[i]- self.nodes[i-1])
return self.result
运行结果
Runtime: 40 ms, faster than 97.70% of Python online submissions for Minimum Absolute Difference in BST.
Memory Usage: 17.6 MB, less than 27.59% of Python online submissions for Minimum Absolute Difference in BST.
原题链接:leetcode.com/problems/mi…
您的支持是我最大的动力