Minimum Distance (Difference) Between BST Nodes
Binary Search Tree
Almost same as Minimum Absolute Difference in BST
Given a Binary Search Tree (BST) with the root noderoot
, return the minimum difference between the values of any two different nodes in the tree.
Example :
Note:
The size of the BST will be between 2 and
100
.The BST is always valid, each node's value is an integer, and each node's value is different.
Solution
In-order Traversal of BST output the node value in sorted order; using a global variable prev to store previous value for comparison.
https://leetcode.com/problems/minimum-distance-between-bst-nodes/solution/
Approach #1: Write to Array
Complexity Analysis
Time Complexity: O(N), where N is the number of nodes in the tree. The complexity comes from the sorting operation.
Space Complexity:O(N), the size of
vals
.
Approach #2: In-Order Traversal
In a binary search tree, an in-order traversal outputs the values of the tree in order. By remembering the previous value in this order, we could iterate over each possible difference, keeping the smallest one.
Complexity Analysis
Time Complexity: O(N), whereNNis the number of nodes in the tree. We iterate over every node once.
Space Complexity: O(H), whereHHis the height of the tree. This is the space used by the implicit call stack when calling
dfs
.
Minimum Distance Between BST Nodes
Last updated