您的位置:首页 > Web前端

Minimum Absolute Difference in BST

2017-02-26 16:07 337 查看
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)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: