Reference: LeetCode
Difficulty: Easy
Problem
Given a binary search tree with non-negative values, find the
minimum absolute difference
between values of any two nodes.
Note: There are at least two nodes in this BST.
Example:
1 | Input: |
Analysis
Methods:
- Brute-Force
- Push into a sorted array.
- Time: $O(N)$
- Space: $O(N)$
- Inorder Traversal
- We need to use the fact that the tree is a BST and inorder traversal will generate sequence in order.
- We compare each nodes with the previous if it exists, and update the minimum difference value if necessary.
- Time: $O(N)$
- Space: $O(h)$
- Preorder Traversal
- We can apply preorder traversal, but this time when traversing the tree, we update
pred
if going right, orsucc
if going left. - During visiting the node, we compare the node’s value with
pred
andsucc
, and update the minimum difference value if necessary. - Time: $O(N)$
- Space: $O(h)$
- We can apply preorder traversal, but this time when traversing the tree, we update
Code
Inorder
Note:
- Initialize
prev
withnull
, since we don’t compare at the beginning. - Use
Math.min
instead of comparison operation. - Don’t forget to update
prev
.
1 | private int minDiff; |
Preorder
Note:
- Initialize
pred
andsucc
withnull
.
1 | private int minDfff; |