AlgoMaster Logo

Minimum Absolute Difference in BST

Ashish

Ashish Pratap Singh

easy

Problem Description

Solve it on LeetCode

Approaches

1. Inorder Traversal with ArrayList

Intuition:

The Binary Search Tree (BST) property ensures that an inorder traversal of the tree will yield nodes in ascending order. By storing these nodes in a list during the traversal, we can then easily compute the minimum absolute difference between consecutive elements.

Steps:

  1. Perform an inorder traversal of the BST to get the nodes in sorted order.
  2. Store the values of the nodes in an ArrayList.
  3. Compute the minimum difference between adjacent elements in the list.

Code:

2. Inorder Traversal with Constant Space

Intuition:

Instead of storing the entire list of values, we can maintain a running track of the previously visited node and compute the minimum difference on-the-fly. This approach utilizes the properties of inorder traversal while reducing space usage.

Steps:

  1. Use a recursive function for the inorder traversal.
  2. Keep track of the previous node's value.
  3. Update the minimum difference during traversal without using additional space for storage.

Code: