题解 | #牛群最小体重差#
牛群最小体重差
https://www.nowcoder.com/practice/e96bd1aad52a468d9bff3271783349c1
考察二叉树的深度优先搜索应用。构建递归函数检查每一个节点并将每次的差值记录,返回所要求的最小差值即可。
完整Java代码如下所示
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整型
*/
ArrayList<Integer> list = new ArrayList<>();
public int getMinimumDifference (TreeNode root) {
// write code here
int res = Integer.MAX_VALUE;
dfs(root);
int temp = list.get(0);
for(int i=1; i<list.size(); i++){
res = Math.min(res, list.get(i)-temp);
temp = list.get(i);
}
return res;
}
public void dfs(TreeNode root){
if(root==null) return;
dfs(root.left);
list.add(root.val);
dfs(root.right);
}
}

查看21道真题和解析
