[LeetCode] Minimum Absolute Difference in BST

news/2024/6/17 14:53:46

Minimum Absolute Difference in BST

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

Inorder Traverse

Time Complexity
O(logn)
Space Complexity
O(1)

思路

Because it is a BST, so the smallest absolute number is near each other by using inorder traverse, keep one global minDiff by traversing the whole tree.

代码

private int minDiff = Integer.MAX_VALUE;
private TreeNode pre = null;
public int getMinimumDifference(TreeNode root) {
    inorder(root);
    return minDiff;
}

private void inorder(TreeNode root){
    if(root == null) return;
    inorder(root.left);
    if(pre != null) minDiff = Math.min(Math.abs(root.val - pre.val), minDiff);
    pre = root;
    inorder(root.right);
}

http://www.niftyadmin.cn/n/2085183.html

相关文章

ABAP OLE XLS

REPORT YGL_MYOLE. INCLUDE OLE2INCL. * OLE OBJECT DATA: MYEXCEL TYPE OLE2_OBJECT, MYSHEET TYPE OLE2_OBJECT, MYCELL TYPE OLE2_OBJECT, MYWORKBOOK TYPE OLE2_OBJECT. ................................. *创建excel进…

CURL的学习和应用

curl安装: xp下面的安装 :修改php.ini文件的设置,找到php_curl.dll //取消下在的注释 extensionphp_curl.dll linux下面安装: # wget http://curl.haxx.se/download/curl-7.17.1.tar.gz # tar zxvf curl-7.17.1.tar.gz //解压 #cd…

推荐软件:Quset PowerGUI

PowerGUI simplifies management via Microsoft Windows PowerShell with an intuitive user console that includes Point, Click, Script™ for quickly building scripts using only a mouse. For more advanced scripting needs, PerfectScript™ provides tools for admin…

camera杂项---两种shutter

什么是快门 快门是照相机用来控制感光片有效曝光时间的机构。是照相机的一个重要组成部分,它的结构、形式及功能是衡量照相机档次的一个重要因素。 什么是Global Shutter(Total Shutter)? 通过整幅场景在同一时间曝光实现的。Se…

心得笔记--色彩空间

在电子领域,常用的东西都可以量化,比如声音,用一秒钟采样声音的幅值48k或者44.1k次,那这些数值记录下来,可以描述一段时间声音。播放的时候可以用这段数据通过adc模拟出来输送到喇叭或者耳机上来。 我们眼睛所看到的大…

AAA配置实例

测试目的:通过AAA,实现用户级的授权 测试环境:TACACS ,1720路由器 测试过程: 实验一:用本地(LOCAL)方法进行验证和授权 配置文件: version 12.1 ! hostname Router ! aaa…

angular学习(七)-- Service

1.7 服务:Service 如果做过后台开发,那么对 Angular 中的服务就好理解多了。 在 Angular 中,服务的概念和后台的服务概念基本是一样的,差别只是在于技术细节。 服务是对公共代码的抽象,比如,如果在多个控制…

安装和使用Glassfish

安装和使用Glassfish Glassfish是Sun Microsystem支持的一个开源社区,它参考了Apache, Eclipse等开源社区的模式,通过OpenSource实现了Java EE 5的全部功能。 Sun的Java System Application PE 9和Java EE 5 SDK即以Glassfish为基础。更多Glassfish的功能…