Given a Binary Search Tree (BST), you need to find the minimum absolute difference between values of any two nodes in the BST.
To find the minimum absolute difference in a BST:
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def getMinimumDifference(root: TreeNode) -> int:
def inorder_traversal(node):
nonlocal prev, min_diff
if not node:
return
inorder_traversal(node.left)
if prev is not None:
min_diff = min(min_diff, node.val - prev)
prev = node.val
inorder_traversal(node.right)
prev = None
min_diff = float('inf')
inorder_traversal(root)
return min_diff
prev
variable to store the value of the previously visited node.prev
.min_diff
if the computed difference is smaller than the current min_diff
.prev
as None
.min_diff
to a large value (float('inf')
), to ensure any actual difference found will be smaller.inorder_traversal
function is called recursively, ensuring the entire tree is traversed and compared.O(n)
where n
is the number of nodes in the BST, as each node is visited once.O(h)
where h
is the height of the tree, due to the recursion stack. In the worst case (unbalanced tree), this could be O(n)
. In the average case (balanced tree), this is O(log n)
.This approach ensures an efficient and straightforward way to compute the minimum absolute difference in a BST.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?