Sponsored
Sponsored
An inorder traversal of a BST yields nodes in non-decreasing order. By performing an inorder traversal, we can collect the values of the nodes in a sorted manner and then iterate through these values to find the minimum difference between successive nodes.
Time Complexity: O(N), where N is the number of nodes in the tree since we visit each node exactly once.
Space Complexity: O(H) due to the recursion stack, where H is the height of the tree.
1class Solution:
2 def __init__(self):
3 self.min_diff = float('inf')
4 self.prev = None
5
6 def minDiffInBST(self, root):
7 self.inorder(root)
8 return self.min_diff
9
10 def inorder(self, node):
11 if not node:
12 return
13 self.inorder(node.left)
14 if self.prev is not None:
15 self.min_diff = min(self.min_diff, node.val - self.prev)
16 self.prev = node.val
17 self.inorder(node.right)
Here, we store the minimum difference and the previous node value as instance variables. As we traverse the tree using inorder, we update these instance variables to compute the minimum difference.
The Morris Traversal is an inorder tree traversal technique that uses constant space by reusing the tree structure. It involves temporarily rearranging the tree to allow traversal without explicit stack use.
Time Complexity: O(N) where each edge is traversed at most twice, once down and once up.
Space Complexity: O(1) because it does not use stack or recursion.
1
Python implementation applies Morris Traversal for an efficient in-order walk, using tree pointers for thread simulation rather than auxiliary space.