Minimum Distance (Difference) Between BST Nodes
Last updated
Was this helpful?
Last updated
Was this helpful?
Binary Search Tree
Almost same as
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.
In-order Traversal of BST output the node value in sorted order; using a global variable prev to store previous value for comparison.
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 ofvals
.
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 callingdfs
.
Minimum Distance Between BST Nodes