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

牛群最小体重差

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

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> list = new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            TreeNode tep = queue.poll();
            list.add(tep.val);
            if (tep.left != null) {
                queue.offer(tep.left);
            }
            if (tep.right != null) {
                queue.offer(tep.right);
            }
        }
        int ans = 10050;
        Integer[] res = list.toArray(new Integer[list.size()]);
        Arrays.sort(res);
        for (int i = 0; i < res.length - 1; i++) {
            if (res[i + 1] - res[i] < ans) {
                ans = res[i + 1] - res[i];
            }
        }
        return ans;
    }
}

本题知识点分析:

1.二叉树的遍历(前序,中序,后序,层序任选其一)

2.有序集合的存取

3.数学模拟

本题解题思路分析:

1.先遍历整个二叉树获取所有的值

2.我用的是中序遍历,这样获取的是递增序列

3.获取所有值后,遍历一次集合,找出最小差值

4.返回最小差值min

本题使用编程语言: Java

全部评论

相关推荐

头像
不愿透露姓名的神秘牛友
04-02 20:12
点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务