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
求的是任意两个节点之间的最小值,先序遍历把数组保存下来,排序之后遍历一遍。