题解 | #牛群最小体重差#
牛群最小体重差
https://www.nowcoder.com/practice/e96bd1aad52a468d9bff3271783349c1?tpId=354&tqId=10591744&ru=/exam/oj&qru=/ta/interview-202-top/question-ranking&sourceUrl=%2Fexam%2Foj
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* public TreeNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类
* @return int整型
*/
public static ArrayList<Integer> arrayList = new ArrayList<>();
public int getMinimumDifference (TreeNode root) {
search(root);
int min = Integer.MAX_VALUE;
for (int i = 1; i < arrayList.size(); i++) {
if (Math.abs(arrayList.get(i) - arrayList.get(i - 1)) < min) {
min = Math.abs(arrayList.get(i) - arrayList.get(i - 1));
}
}
return min;
}
public void search(TreeNode root) {
if (root == null) {
return;
}
search(root.left);
arrayList.add(root.val);
search(root.right);
}
}
本题知识点分析:
1.二叉树的遍历(前序,中序,后序,层序任选其一)
2.有序集合的存取
3.数学模拟
本题解题思路分析:
1.先遍历整个二叉树获取所有的值
2.我用的是中序遍历,这样获取的是递增序列
3.获取所有值后,遍历一次集合,找出最小差值
4.返回最小差值min
本题使用编程语言: Java
如果本篇文章对您有帮助的话,可以点个赞支持一下,感谢~

查看7道真题和解析