Grokking Data Structures & Algorithms for Coding Interviews
0% completed
Solution: Minimum Difference Between BST Nodes
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 so that the value of every node on the left is less than the root, and the value of every node on the right is greater than the root. All values are distinct, which matters here: the question asks for the smallest difference between two different nodes, and duplicates would make that difference 0.
Example
Example 1:
- Input:
4
/ \
2 6
/ \
1 3
- Expected Output: 1
.....
.....
.....
Like the course? Get enrolled and start learning!
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); } }
Show 1 reply
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
Show 1 reply
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 3 replies
Reading Progress
0%