leectcode第530题,竞赛题的签到题,比赛居然不会做。。。
主要是基本的数据结构还不熟,这里要求求一个二叉搜索树节点直接数值绝对差的最小值。注意,节点间是指所有节点之间,不是相邻节点之间。
这里很明显要用到二叉搜索树的一个性质,那就是二叉搜索树中序遍历会得到一个有序数组,这样一来,绝对值差肯定是这个数组相邻两个数的差里面的最小值了。
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def getMinimumDifference(self, root):
"""
:type root: TreeNode
:rtype: int
"""
def inOreder(node, nodeList):
if node.left != None:
inOreder(node.left, nodeList)
nodeList.append(node.val)
if node.right != None:
inOreder(node.right, nodeList)
nodeList = []
inOreder(root, nodeList)
n = len(nodeList)
absDiff = []
for i in range(n-1):
absDiff.append(nodeList[i+1]-nodeList[i])
return min(absDiff)