530. 二叉搜索树的最小绝对差

注意:

二叉搜索树的性质:
任意节点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)

相关文章:

  • 2022-12-23
  • 2021-11-17
  • 2022-12-23
  • 2022-12-23
  • 2021-10-26
  • 2021-12-18
  • 2022-12-23
猜你喜欢
  • 2021-05-31
  • 2022-01-14
  • 2021-08-30
  • 2021-10-16
  • 2021-10-23
  • 2021-05-30
  • 2018-10-10
相关资源
相似解决方案