LeetCode530. 二叉搜索树的最小绝对差
- 题目链接
- 代码
题目链接
https://leetcode.cn/problems/minimum-absolute-difference-in-bst/
代码
递归
# 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 0result = 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 = rootresult = float('inf')pre = Nonewhile cur is not None or len(stack) > 0:if cur is not None:stack.append(cur)cur = cur.leftelse:cur = stack.pop()if pre is not None:result = min(result, cur.val - pre.val)pre = curcur = cur.rightreturn result