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

牛群最小体重差

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

知识点:二叉搜索树,中序遍历

对于二叉搜索树来说,中序遍历即为元素升序排列的结果,题目要求找到元素间的最小差值,而我们通过中序遍历可以得到元素升序排列的结果,故我们只需要比较中序遍历中相邻的两个节点值,通过相邻的节点值来寻找元素间的最小差值,具体来说,定义一个节点pre,初始为空,每次将其赋值为上一个遍历过的节点,从而计算两个节点间的差值。

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

    private TreeNode pre = null;
    private int diff = Integer.MAX_VALUE;

    public int getMinimumDifference (TreeNode root) {
        // write code here
        order(root);
        return diff;
    }

    private void order(TreeNode root) {
        if(root == null) {
            return;
        }
        order(root.left);
        if(pre != null) {
            diff = Math.min(diff, root.val - pre.val);
        }
        pre = root;
        order(root.right);
    }
}

全部评论

相关推荐

明天不下雨了:兄弟你是我今天看到的最好看的简历(我说的是简历风格跟简历书写)把985 211再搞亮一点。投boss就说;您好,我华科(985)研二在读,本科211。对您的岗位很感兴趣,希望能获得一次投递机会。
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务