注意:
二叉搜索树的性质:
任意节点x,其左子树中的key不大于x.key,其右子树中的key不小于x.key。
因此,中间节点的值一定是其左右节点值的中间数,因此最小差别一定是在中间节点与左右节点之间
思路: 中序遍历二叉搜索树,每次比较当前节点与前一节点差值的绝对值与目前result中保存的最小值的大小,将较小的保存在result中。
第一直觉:用 gloabal 辅助中序遍历
80秒
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def getMinimumDifference(self, root):
"""
:type root: TreeNode
:rtype: int
"""
global res
res = []
results = self.inorder(root)
length = len(results)
mn = results[1]-results[0]
for i in range(1,length):
cur = results[i]
la = results[i-1]
mn = min(mn, cur-la)
return mn
def inorder(self, root):
if root is None:
return
self.inorder(root.left)
res.append(root.val)
self.inorder(root.right)
return res
第二、简便实现中序遍历
88秒
def inorder(self,root):
if not root:
return []
return self.inorder(root.left) + [root.val] + self.inorder(root.right)
第三参考、 用 yield 实现中序遍历,输出值是个迭代对象
84秒
class Solution:
def getMinimumDifference(self, root):
"""
:type root: TreeNode
:rtype: int
"""
gen = self.inorder(root)
x= next(gen)
last = next(gen)
mn = last -x
for i in gen:
mn =min(mn,i-last)
last = i
return mn
def inorder(self,root):
if root.left:
yield from self.inorder(root.left)
yield root.val
if root.right:
yield from self.inorder(root.right)