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

牛群最小体重差

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整型
     */

    public static int cnt = Integer.MAX_VALUE;
    public static int tmp = Integer.MIN_VALUE+10001;
    public void inorder(TreeNode root) {
        if (root == null)
            return;
        inorder(root.left);
        cnt = Math.min(cnt, root.val - tmp);
        tmp = root.val;
        inorder(root.right);
    }
    public int getMinimumDifference (TreeNode root) {
        // write code here
        inorder(root);
        return cnt;
    }
}

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务