[
bst
tree
stack
]
Leetcode 0530 Minimum Absolute Difference in BST
Problem statement
https://leetcode.com/problems/minimum-absolute-difference-in-bst/
Solution
Just use any inorder traversal of tree, either using recursion, or using stack and keep traversed array, which will be increasing.
Complexity
Time complexity is O(n)
, space complexity as well. Space complexityis O(h)
, where h
is height of tree, because we can keep only two last elements each moment of time.
Code
class Solution:
def getMinimumDifference(self, root):
pre, ans, stack = -float("inf"), float("inf"), []
while stack or root:
while root:
stack.append(root)
root = root.left
root = stack.pop()
pre, ans = root.val, min(ans, root.val - pre)
root = root.right
return ans
Remark
Space complexity can be reduced to O(1)
if we use Morrison traversal.