问题

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/4123 访问。

给定一个所有节点为非负值的二叉搜索树,求树中任意两节点的差的绝对值的最小值。

输入:

1

    \

     3

    /

   2

输出:

1

解释:

最小绝对差为1,其中 2 和 1 的差的绝对值为 1(或者 2 和 3)。

注意: 树中至少有2个节点。


Given a binary search tree with non-negative values, find the minimum absolute difference between values of any two nodes.

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.


示例

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/4123 访问。

public class Program {

    public static void Main(string[] args) {
var root = new TreeNode(4) {
left = new TreeNode(8),
right = new TreeNode(1)
}; var res = GetMinimumDifference(root);
Console.WriteLine(res); Console.ReadKey();
} public static int GetMinimumDifference(TreeNode root) {
var list = new List<int>();
PreOrder(root, ref list);
var res = int.MaxValue;
list.Sort();
for(var i = 0; i < list.Count - 1; i++) {
res = Math.Min(res, list[i + 1] - list[i]);
}
return res;
} public static void PreOrder(TreeNode root, ref List<int> list) {
if(root == null) return;
list.Add(root.val);
PreOrder(root?.left, ref list);
PreOrder(root?.right, ref list);
} public class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int x) { val = x; }
} }

以上给出1种算法实现,以下是这个案例的输出结果:

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/4123 访问。

3

分析:

对于该题来说,虽然使用了运行库 list.Sort() 排序,但 GetMinimumDifference 方法中最耗时且最重要的步骤是 res = Math.Min(res, list[i + 1] - list[i]) 这一句代码,所以我认为以上算法的时间复杂度应当为:  。

最新文章

  1. 【CodeVS2800】 送外卖 最短路+状压DP
  2. MVC之前的那点事儿系列(9):MVC如何在Pipeline中接管请求的?
  3. 转:linux下bwa和samtools的安装与使用
  4. [转]发送邮件提示“551 User not local; please try ”错误的原因及解决办法
  5. python与unicode
  6. Android内存管理(3)缓存不要用SoftReference, 用android.util.LruCache
  7. vs中的主题配置
  8. HDU4608+模拟
  9. C# 多线程使用队列注意事项
  10. acdream 1222 Quantization Problem [dp]
  11. 如何有效的遍历django的QuerySet
  12. Linux_Cytoscape
  13. MySQL的GROUP_CONCAT函数
  14. [转]mysql优化——show processlist命令详解
  15. GBDT原理
  16. day45
  17. 腾讯优图联手Science发布主题报告:计算机视觉的研发和应用
  18. LeetCode题解之Rotate Array
  19. js 中实现aop
  20. Scala入门4(_的用法)

热门文章

  1. vpp之clib.h分析
  2. 入门大数据---Hive计算引擎Tez简介和使用
  3. iview实战 : 全屏去头去尾的弹窗
  4. css : 使用浮动实现左右各放一个元素时很容易犯的错误
  5. 加班两个星期做的一个小系统~(winform)
  6. Dubbo的负载均衡算法源码分析
  7. element-ui的el-progress组件增加修改status状态
  8. 一个在raw里面放着数据库文件的网上例子
  9. SpringBoot实现前后端数据交互、json数据交互、Controller接收参数的几种常用方式
  10. KMP算法图解