LeetCode(力扣)530. 二叉搜索树的最小绝对差Python

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

    • 题目链接
    • 代码

题目链接

https://leetcode.cn/problems/minimum-absolute-difference-in-bst/
LeetCode(力扣)530. 二叉搜索树的最小绝对差Python_第1张图片

代码

递归

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def __init__(self):
        self.vec = []
    def traversal(self, root):
        if root is None:
            return 
        self.traversal(root.left)
        self.vec.append(root.val)
        self.traversal(root.right)

    def getMinimumDifference(self, root: Optional[TreeNode]) -> int:
        self.vec = []
        self.traversal(root)

        if len(self.vec) < 2:
            return 0
        result = float('inf')
        
        for i in range(len(self.vec) - 1):
            result = min(result, (self.vec[i + 1] - self.vec[i]))
        return result

迭代

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def getMinimumDifference(self, root: Optional[TreeNode]) -> int:
        stack = []
        cur = root
        result = float('inf')
        pre = None
        while cur is not None or len(stack) > 0:
            if cur is not None:
                stack.append(cur)
                cur = cur.left
            else:
                cur = stack.pop()
                if pre is not None:
                    result = min(result, cur.val - pre.val)
                pre = cur
                cur = cur.right
        return result

你可能感兴趣的:(leetcode,python,算法,职场和发展,开发语言)