描述
给定一个二叉搜索树的根结点 root, 返回树中任意两节点的差的最小值。
样例 1:
输入: root = {4,2,6,1,3}
输出: 1
样例 2:
输入: root = {2,1}
输出: 1
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: a Binary Search Tree (BST) with the root node
@return: the minimum difference
"""
def minDiffInBST(self, root):
# Write your code here.
a = []
s = Solution()
s.add_to_list(root, a)
a.sort()
b = []
for i in range(1,len(a)):
b.append(abs(a[i] - a[i-1]))
b.sort()
return b[0]
def add_to_list(self,root,a:list):
if root == None:
return
a.append(root.val)
s = Solution()
s.add_to_list(root.left, a)
s.add_to_list(root.right, a)
return