Leetcode 530.二叉搜索树的最小绝对差(Minimum Absolute Difference in BST)

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

1 题目描述(Leetcode题目链接

  给你一棵所有节点为非负值的二叉搜索树,请你计算树中任意两节点的差的绝对值的最小值。

输入:

   1
    \
     3
    /
   2

输出:
1

解释:
最小绝对差为 1,其中 21 的差的绝对值为 1(或者 23)。

提示:树中至少有 2 个节点。

2 题解

  中序遍历即可。更多信息可见二叉搜索树

# 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: TreeNode) -> int:
        pre = float("-inf")
        retv = float("inf")
        stack = []
        while root or stack:
            while root:
                stack.append(root)
                root = root.left
            root = stack.pop()
            retv = min(retv, root.val - pre)
            pre = root.val
            root = root.right
        return retv
发布了264 篇原创文章 · 获赞 63 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_39378221/article/details/105064432