力扣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);

}

}

相关推荐
SHUIPING_YANG4 分钟前
根据用户id自动切换表查询
java·服务器·数据库
Norvyn_76 分钟前
LeetCode|Day18|20. 有效的括号|Python刷题笔记
笔记·python·leetcode
爱吃烤鸡翅的酸菜鱼16 分钟前
IDEA高效开发:Database Navigator插件安装与核心使用指南
java·开发语言·数据库·编辑器·intellij-idea·database
惊涛骇浪、22 分钟前
SpringMVC + Tomcat10
java·tomcat·springmvc
呆呆的小鳄鱼35 分钟前
leetcode:冗余连接 II[并查集检查环][节点入度]
算法·leetcode·职场和发展
墨染点香35 分钟前
LeetCode Hot100【6. Z 字形变换】
java·算法·leetcode
沧澜sincerely36 分钟前
排序【各种题型+对应LeetCode习题练习】
算法·leetcode·排序算法
CQ_071236 分钟前
自学力扣:最长连续序列
数据结构·算法·leetcode
弥彦_1 小时前
cf1925B&C
数据结构·算法
ldj20201 小时前
SpringBoot为什么使用new RuntimeException() 来获取调用栈?
java·spring boot·后端