530. 二叉搜索树的最小绝对差
给定一个所有节点为非负值的二叉搜索树,求树中任意两节点的差的绝对值的最小值。
示例 :
输入:
1
\
3
/
2
输出:
1
解释:
最小绝对差为1,其中 2 和 1 的差的绝对值为 1(或者 2 和 3)。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/minimum-absolute-difference-in-bst
1 public class MinimumAbsoluteDiffernceInBST530 { 2 static class TreeNode { 3 int val; 4 TreeNode left; 5 TreeNode right; 6 TreeNode(int x) { 7 val = x; 8 } 9 } 10 11 /* private int minDiff = Integer.MAX_VALUE; 12 public int getMinimumDifference(TreeNode root) { 13 TreeNode preNode = null; 14 inOrder(root, preNode); 15 return minDiff; 16 } 17 public void inOrder(TreeNode root, TreeNode preNode) { 18 if(root == null) { 19 return; 20 } 21 inOrder(root.left, preNode); 22 if(preNode != null) { 23 minDiff = Math.min(minDiff, root.val - preNode.val); 24 } 25 preNode = root; 26 inOrder(root.right, preNode); 27 } 28 29 public static void main(String[] args) { 30 MinimumAbsoluteDiffernceInBST530 test = new MinimumAbsoluteDiffernceInBST530(); 31 TreeNode root = new TreeNode(5); 32 root.left = new TreeNode(4); 33 root.right = new TreeNode(7); 34 System.out.println(test.getMinimumDifference(root)); 35 }*/ 36 private int minDiff = Integer.MAX_VALUE; 37 private TreeNode preNode = null; 38 public int getMinimumDifference(TreeNode root) { 39 inOrder(root); 40 return minDiff; 41 } 42 public void inOrder(TreeNode root) { 43 if(root == null) { 44 return; 45 } 46 inOrder(root.left); 47 if(preNode != null) { 48 minDiff = Math.min(minDiff, root.val - preNode.val); 49 } 50 preNode = root; 51 inOrder(root.right); 52 } 53 54 public static void main(String[] args) { 55 MinimumAbsoluteDiffernceInBST530 test = new MinimumAbsoluteDiffernceInBST530(); 56 TreeNode root = new TreeNode(5); 57 root.left = new TreeNode(4); 58 root.right = new TreeNode(7); 59 System.out.println(test.getMinimumDifference(root)); 60 } 61 }
无论有多困难,都坚强的抬头挺胸,人生是一场醒悟,不要昨天,不要明天,只要今天。不一样的你我,不一样的心态,不一样的人生,顺其自然吧