题解 | #牛群最小体重差#

牛群最小体重差

https://www.nowcoder.com/practice/e96bd1aad52a468d9bff3271783349c1

知识点

树,集合

解题思路

将树的节点全部放到list集合中,对list集合排序,比较相邻两个节点,获取其中最小的差值。

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整型
     */
    List<Integer> list = new ArrayList<>();
    public int getMinimumDifference (TreeNode root) {
        // write code here
        fun(root);
        Collections.sort(list);
        int ans = Integer.MAX_VALUE;
        for(int i = 1; i < list.size(); i++){
            ans = Math.min(ans,list.get(i) - list.get(i - 1));
        }
        return ans;
    }
    public void fun(TreeNode root){
        if(root != null) {
            list.add(root.val);
            fun(root.left);
            fun(root.right);
        }
    }
}

全部评论

相关推荐

废物一个0offer:认真的吗二本本科找人工智能岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务