[LeetCode] 530. Minimum Absolute Difference in BST Java
阿新 • • 發佈:2017-09-14
lis https root ren str void init 搜索樹 dia
題目:
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.
題意及分析:給出一顆二叉搜索樹(節點為非負),要求求出任意兩個點之間差值絕對值的最小值。題目簡單,直接中序遍歷二叉樹,得到一個升序排列的list,然後計算每兩個數差的絕對值,每次和當前最小值進行比較,若小於當前最小值,替換掉即可。
代碼:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public int getMinimumDifference(TreeNode root) { //中根序遍歷,然後比較每相鄰的兩個數 List<Integer> list = new ArrayList<>(); search(list,root); int min = Integer.MAX_VALUE; for(int i=0;i<list.size()-1;i++){ int temp = Math.abs(list.get(i+1)-list.get(i)); if(temp<min) min = temp; } return min; } private void search( List<Integer> list,TreeNode node){ if(node!=null){ search(list,node.left); list.add(node.val); search(list,node.right); } } }
[LeetCode] 530. Minimum Absolute Difference in BST Java