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

}

}

相关推荐
py有趣几秒前
力扣热门100题之零钱兑换
算法·leetcode
董董灿是个攻城狮18 分钟前
Opus 4.7 来了,我并不建议你升级
算法
自我意识的多元宇宙23 分钟前
二叉树遍历方式代码解读(2迭代)
数据结构
无敌昊哥战神1 小时前
【保姆级题解】力扣17. 电话号码的字母组合 (回溯算法经典入门) | Python/C/C++多语言详解
c语言·c++·python·算法·leetcode
脱氧核糖核酸__1 小时前
LeetCode热题100——238.除了自身以外数组的乘积(题目+题解+答案)
数据结构·c++·算法·leetcode
再卷也是菜1 小时前
算法提高篇(1)线段树(上)
数据结构·算法
py有趣1 小时前
力扣热门100题之单词拆分
算法·leetcode
杨凯凡1 小时前
【012】图与最短路径:了解即可
java·数据结构
比特森林探险记1 小时前
【无标题】
java·前端
椰猫子2 小时前
Javaweb(Filter、Listener、AJAX、JSON)
java·开发语言