
Minimum Absolute Difference in BST
返回一个 BST 任意两数的最小差值
Solution
原本想不到怎么比较最小的那个节点,想着用一个 List 存下来
看到别人用一个Integer对象存起来,觉得挺好的。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
|
public class { int diff = Integer.MAX_VALUE; Integer min = null; public int getMinimumDifference(TreeNode root) { if(root == null && root.left == null && root.right == null) { return 0; } dfs(root); return diff; } private void dfs(TreeNode root) { if(root == null) { return; } dfs(root.left); if(min != null) { diff = Math.min(diff, root.val - min); } min = root.val; dfs(root.right); } }
|
近期评论