题目链接
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 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