| | 1 | | // -------------------------------------------------------------------------------- |
| | 2 | | // Copyright (C) 2025 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | 3 | | // All Rights Reserved. |
| | 4 | | // -------------------------------------------------------------------------------- |
| | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | 9 | | // known as Yevhenii Yeriemeieiv). |
| | 10 | | // -------------------------------------------------------------------------------- |
| | 11 | |
|
| | 12 | | using LeetCode.Core.Models; |
| | 13 | |
|
| | 14 | | namespace LeetCode.Algorithms.MinimumAbsoluteDifferenceInBST; |
| | 15 | |
|
| | 16 | | /// <inheritdoc /> |
| | 17 | | public class MinimumAbsoluteDifferenceInBSTDepthFirstSearch : IMinimumAbsoluteDifferenceInBST |
| | 18 | | { |
| | 19 | | /// <summary> |
| | 20 | | /// Time complexity - O(n) |
| | 21 | | /// Time complexity - O(n) for a skewed tree, O(log n) for a balanced tree |
| | 22 | | /// </summary> |
| | 23 | | /// <param name="root"></param> |
| | 24 | | /// <returns></returns> |
| | 25 | | public int GetMinimumDifference(TreeNode root) |
| 3 | 26 | | { |
| 3 | 27 | | TreeNode? prev = null; |
| | 28 | |
|
| 3 | 29 | | return GetMinimumDifference(root, ref prev, int.MaxValue); |
| 3 | 30 | | } |
| | 31 | |
|
| | 32 | | private static int GetMinimumDifference(TreeNode node, ref TreeNode? prev, int minDiff) |
| 15 | 33 | | { |
| 15 | 34 | | if (node.left != null) |
| 6 | 35 | | { |
| 6 | 36 | | minDiff = GetMinimumDifference(node.left, ref prev, minDiff); |
| 6 | 37 | | } |
| | 38 | |
|
| 15 | 39 | | if (prev != null) |
| 12 | 40 | | { |
| 12 | 41 | | minDiff = Math.Min(minDiff, node.val - prev.val); |
| 12 | 42 | | } |
| | 43 | |
|
| 15 | 44 | | prev = node; |
| | 45 | |
|
| 15 | 46 | | if (node.right != null) |
| 6 | 47 | | { |
| 6 | 48 | | minDiff = GetMinimumDifference(node.right, ref prev, minDiff); |
| 6 | 49 | | } |
| | 50 | |
|
| 15 | 51 | | return minDiff; |
| 15 | 52 | | } |
| | 53 | | } |