题解 | #牛群最小体重差#
牛群最小体重差
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); } }