题目:
Given a binary search tree with non-negative values, find the minimum absolute difference between values of any two nodes.
Example:
Input: 1 3 / 2 Output: 1 Explanation: The minimum absolute difference is 1, which is the difference between 2 and 1 (or between 2 and 3).
Note: There are at least two nodes in this BST.
链接:https://leetcode.com/problems/minimum-absolute-difference-in-bst/#/description
3/31/2017
16ms, 79%
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public int getMinimumDifference(TreeNode root) { 12 ArrayList<Integer> list = new ArrayList<Integer>(); 13 inOrderTraversal(root, list) ; 14 int minDiff = Integer.MAX_VALUE; 15 16 for(int i = 1; i < list.size(); i++) { 17 if (list.get(i) - list.get(i - 1) < minDiff) minDiff = list.get(i) - list.get(i - 1); 18 } 19 return minDiff; 20 } 21 private void inOrderTraversal(TreeNode root, ArrayList<Integer> list) { 22 if (root == null) return; 23 inOrderTraversal(root.left, list); 24 list.add(root.val); 25 inOrderTraversal(root.right, list); 26 } 27 }
别人的解法,其中有关于BT的问题
不需要用inorder traversal的方法,只需要跟前后值比较
更多讨论:
https://discuss.leetcode.com/category/680/minimum-absolute-difference-in-bst