力扣530 补9.12

530.二叉搜索树的最小绝对差

可以做,就是中序遍历,把数从小到大排序,再循环找最小值。

再或者一个个遍历每个结点,把他跟父结点和爷结点比大小,更新最小值,因为要么左边要么右边跟中间节点比大小,不会让左边跟右边比大小。

class Solution {

int num=0;

int[] a=new int[10000];

int ans=100000;

public int getMinimumDifference(TreeNode root) {

if(root==null){

return 0;

}

dfs(root);

// for(int i=0;i<num;i++){

// System.out.println(a[i]);

// }

// System.out.println(num);

for(int i=0;i<num-1;i++){

ans=Math.min(a[i+1]-a[i],ans);

}

return ans;

}

void dfs(TreeNode root){

if(root==null) return;

dfs(root.left);

a[num++]=root.val;

// System.out.println(num);

dfs(root.right);

}

}

相关推荐
VX:Fegn089541 分钟前
计算机毕业设计|基于springboot + vue智慧医药系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端·课程设计
两个蝴蝶飞5 小时前
Java量化系列(四):实现自选股票维护功能
java·经验分享
短剑重铸之日7 小时前
7天读懂MySQL|Day 5:执行引擎与SQL优化
java·数据库·sql·mysql·架构
酒九鸠玖7 小时前
Java--多线程
java
Dreamboat-L7 小时前
云服务器上部署nginx
java·服务器·nginx
长安er7 小时前
LeetCode215/347/295 堆相关理论与题目
java·数据结构·算法·leetcode·
元亓亓亓8 小时前
LeetCode热题100--62. 不同路径--中等
算法·leetcode·职场和发展
小白菜又菜8 小时前
Leetcode 1925. Count Square Sum Triples
算法·leetcode
粉红色回忆8 小时前
用链表实现了简单版本的malloc/free函数
数据结构·c++
cici158748 小时前
C#实现三菱PLC通信
java·网络·c#