Today, I tried to solve a problem from LeetCode called “783. Minimum Distance Between BST Nodes”. Let me share my experience with you.
First, I opened LeetCode and found the problem. I carefully read the problem description. It asked to find the minimum difference between the values of any two different nodes in a given Binary Search Tree (BST).
Okay, I thought, it’s a BST, so the inorder traversal should give me the node values in a sorted order. I remembered that! If I can get the values in sorted order, then I just need to find the smallest difference between consecutive values. That seemed like a good plan.
So, I started coding. I wrote a function for inorder traversal. This function recursively visits the left subtree, then the current node, and finally the right subtree. As I visited each node, I added its value to a list.
Here’s a snippet that looks like the core recursive part I did:
- inorder(*)
- inorder(*)
After I got the sorted list of node values, I initialized a variable `minDiff` to a really large number. Then, I iterated through the list, comparing the difference between each consecutive pair of values with `minDiff`. If I found a smaller difference, I updated `minDiff`. Simple!
Here’s the pseudo snippet for iterating part I made:
- for i = 1; i less than list size ; i++
- minDiff = min( minDiff , list at index (i) minus list at index (i minus 1))
Finally, I returned `minDiff`. That’s it!
I tested my code with some sample inputs and it worked fine. Then, I submitted it to LeetCode, and… yay! It got accepted! It wasn’t super fast, but it was good enough. I felt pretty good about solving this problem.
It was a good exercise to refresh my understanding of BSTs and inorder traversal. It reminded me how useful inorder traversal can be for problems involving sorted values in a BST.