Skip to content

Commit 1d9dd5b

Browse files
committed
https://leetcode.com/problems/minimum-absolute-difference-in-bst/
1 parent 47f9bdb commit 1d9dd5b

File tree

3 files changed

+50
-2
lines changed

3 files changed

+50
-2
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
namespace LeetCodeSolutions.BinarySearchTree;
2+
3+
public class MinimumAbsoluteDifferenceInBst
4+
{
5+
public int GetMinimumDifference(TreeNode root)
6+
{
7+
return InorderTraversal(root, int.MaxValue, null).minDiff;
8+
}
9+
10+
private (int minDiff, TreeNode prev) InorderTraversal(TreeNode root, int minDiff, TreeNode prev)
11+
{
12+
if (root == null)
13+
{
14+
return (minDiff, prev);
15+
}
16+
17+
(minDiff, prev) = InorderTraversal(root.left, minDiff, prev);
18+
19+
if (prev != null)
20+
{
21+
minDiff = Math.Min(minDiff, root.val - prev.val);
22+
}
23+
24+
prev = root;
25+
26+
return InorderTraversal(root.right, minDiff, prev);
27+
}
28+
29+
[Test(Description = "https://leetcode.com/problems/minimum-absolute-difference-in-bst/")]
30+
[Category("Easy")]
31+
[Category("LeetCode")]
32+
[Category("Minimum absolute difference in BST")]
33+
[TestCaseSource(nameof(Input))]
34+
[Category("Binary Search Tree")]
35+
[Category("TopInterview")]
36+
public void Test1((int Output, int?[] Input) item)
37+
{
38+
var response = GetMinimumDifference(item.Input.ToTreeNode());
39+
Assert.That(response, Is.EqualTo(item.Output));
40+
}
41+
42+
public static IEnumerable<( int Output, int?[] Input)> Input =>
43+
new List<(int Output, int?[] Input)>()
44+
{
45+
(9, [236, 104, 701, null, 227, null, 911]),
46+
(1, [4, 2, 6, 1, 3]),
47+
(1, [1, 0, 48, null, null, 12, 49]),
48+
};
49+
}

LeetCodeSolutions/LeetCodeSolutions.csproj

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@
1414
</ItemGroup>
1515
<ItemGroup>
1616
<Folder Include="Backtracking\" />
17-
<Folder Include="BinarySearchTree\" />
1817
<Folder Include="GraphBfs\" />
1918
<Folder Include="Graph\" />
2019
<Folder Include="Heap\" />

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -139,7 +139,7 @@ The Top Interview 150 collection on Leetcode is a curated set of 150 interview q
139139
| 84 | Binary Tree Level Order Traversal | Medium | |
140140
| 85 | Binary Tree Zigzag Level Order Traversal | Medium | |
141141
| <br> Binary Search Tree<br> | | | |
142-
| 86 | Minimum Absolute Difference in BST | Easy | |
142+
| 86 | Minimum Absolute Difference in BST | Easy | |
143143
| 87 | Kth Smallest Element in a BST | Medium | |
144144
| 88 | Validate Binary Search Tree | Medium | |
145145
| <br> Graph General<br> | | | |

0 commit comments

Comments
 (0)