题解 | #牛群最小体重差#
牛群最小体重差
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 int getMinimumDifference (TreeNode root) {
// write code here
List<Integer> values = new ArrayList<>();
inOrderTraversal(root, values);
int minDifference = Integer.MAX_VALUE;
for (int i = 1; i < values.size(); i++) {
minDifference = Math.min(minDifference, values.get(i) - values.get(i - 1));
}
return minDifference;
}
private void inOrderTraversal(TreeNode root, List<Integer> values) {
if (root == null) {
return;
}
inOrderTraversal(root.left, values);
values.add(root.val);
inOrderTraversal(root.right, values);
}
}
知识点:
基本的Java语法和概念。
二叉搜索树的遍历和性质。
解题思路:
在minDiffInBST方法中,我们首先调用中序遍历方法,将二叉搜索树的节点值按升序顺序存储在列表values中。然后,我们遍历values列表,计算相邻节点值之间的差值,找到最小的差值并返回。

腾讯成长空间 5958人发布