Grokking Data Structures & Algorithms for Coding Interviews
Vote
0% completed
Minimum Difference Between BST Nodes (easy)
Problem Statement
Given a Binary Search Tree (BST), you are required to find the smallest difference between the values of any two different nodes.
In a BST, the nodes are arranged in a manner where the value of nodes on the left is less than or equal to the root, and the value of nodes on the right is greater than the root.
Example
Example 1:
- Input:
4
/ \
2 6
/ \
1 3
- Expected Output: 1
- Justification: The pairs (1,2), (2,3), or (3,4) have the smallest difference of 1.
Example 2:
- Input:
10
/ \
5 15
/ \ \
2 7 18
.....
.....
.....
Like the course? Get enrolled and start learning!
H
Hamidou Diallo
· 2 years ago
class Solution: def __init__(self): self.min_diff = float('inf') self.prev = None def minDiffInBST(self, root): if not root: return self.min_diff self.minDiffInBST(root.left) if self.prev: node_diff = abs(root.val - self.prev.val) self.min_diff = min(self.min_diff, node_diff) self.prev = root self.minDiffInBST(root.right) return self.min_diff
Anand Nageshwar Kumar
· 2 years ago
public class Solution { int result = Int32.MaxValue; int? prev = null; public int GetMinimumDifference(TreeNode root) { DFS(root); return result; } private void DFS(TreeNode root) { if(root == null) return; DFS(root.left); if(prev.HasValue) result = Math.Min(result, root.val - prev.Value); prev = root.val; DFS(root.right); } }
Elena Feoktistova
· 3 years ago
public class Solution { public int minDiffInBST(TreeNode root) { int minDiff = Integer.MAX_VALUE; TreeNode prev = null; Stack<TreeNode> stack = new Stack<>(); TreeNode curr = root; while (curr != null || !stack.isEmpty()) { while (curr != null) { stack.push(curr); curr = curr.left; } curr = stack.pop(); if (prev != null) { minDiff = Math.min(curr.val - prev.val, minDiff); } prev = curr; curr = curr.right; } return minDiff; } }
Show 2 replies