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 34
|
class Solution { public int minDiffInBST(TreeNode root) { List<Integer> list = new ArrayList<>(); dfs(root, list); list.sort((a, b) -> a - b); int ans = Integer.MAX_VALUE; for (int i = 1; i < list.size(); ++i) { ans = Math.min(ans, Math.abs(list.get(i - 1) - list.get(i))); } return ans; }
private void dfs(TreeNode root, List<Integer> list) { if (root == null) return; list.add(root.val); dfs(root.left, list); dfs(root.right, list); } }
|