Given a binary search tree with non-negative values, find the minimum absolute difference between values of any two nodes.
Example:
Input: 1 3 / 2 Output: 1 Explanation: The minimum absolute difference is 1, which is the difference between 2 and 1 (or between 2 and 3).
Note: There are at least two nodes in this BST.
暴力解法,但是会超时
private readonly List<int> deltaList = new List<int>(); private readonly List<int> sourceList = new List<int>(); public int GetMinimumDifference(TreeNode root) { Chuck(root); int min = deltaList.Min(); return min; } private void Chuck(TreeNode node) { if (node == null) { return; } int val = node.val; if (!sourceList.Contains(val)) { foreach (var item in sourceList) { var delta = Math.Abs(item - val); if (!deltaList.Contains(delta)) { deltaList.Add(delta); } } sourceList.Add(val); } else { deltaList.Add(0); } Chuck(node.left); Chuck(node.right); }
https://www.cnblogs.com/grandyang/p/6540165.html
由于BST的左<根<右的性质可知,如果按照中序遍历会得到一个有序数组,那么最小绝对差肯定在相邻的两个节点值之间产生。
所以我们的做法就是对BST进行中序遍历,然后当前节点值和之前节点值求绝对差并更新结果res。
https://anothercasualcoder.blogspot.com/2017/06/minimum-absolute-difference-in-bst-by.html
It is important to use the only crucial information in this problem: that we're dealing with a Binary-Search-Tree (BST). With that information in mind, remember that an In-Order traversal of the tree will give you all its elements in sorted order. If your tree for instance is:
6
3 7
The In-Order traversal will give you 3,6,7. Now with that it becomes very easy to solve it:
a) Do an In-Order traversal passing in the previous value
b) The processing will consist of checking <current value> - <previous value> and keeping tracking of the min
Linear time, very fast as the response indicates. Code is down below - cheers! Marcelo
public int GetMinimumDifference(TreeNode root) { int res = int.MaxValue ,pre = -1; Chuck(root,ref pre, ref res); return res; } private void Chuck(TreeNode node, ref int pre, ref int res) { if (node == null) { return; } Chuck(node.left, ref pre, ref res); if (pre != -1) { res = Math.Min(res, node.val - pre); } pre = node.val; Chuck(node.right, ref pre, ref res); }
Runtime: 104 ms, faster than 69.42% of C# online submissions forMinimum Absolute Difference in BST.
Memory Usage: 26.2 MB, less than 33.33% of C# online submissions forMinimum Absolute Difference in BST.
注意事项
prev必须是ref类型,
[5,4,7]
5
/
4 7
不是ref类型,左边在递归的时候,退出时会丢失value
prev = -1
prev = -1
prev = 5
7 - 5 = 2
2
ref类型
prev = -1
prev = 4
5 - 4 = 1
prev = 5
7 - 5 = 2
1
使用全局变量
private int pre = -1; private int res = int.MaxValue; public int GetMinimumDifference(TreeNode root) { Chuck(root); return res; } private void Chuck(TreeNode node) { if (node == null) { return; } Chuck(node.left); Output.WriteLine($"prev = {pre}"); if (pre != -1) { int delta = node.val - pre; Output.WriteLine($"{node.val} - {pre} = {delta}"); res = Math.Min(res, delta); } pre = node.val; Chuck(node.right); }