LeetCode 530 Minimum Absolute Difference in BST
- 2019 年 12 月 29 日
- 筆記
題意
給予一顆非負二叉搜索樹, 返回任意兩個節點之間的最小相差值.
注: 樹至少有兩個節點.
例 :
給予樹: 1 4 / 2 7 返回: 1 (1 和 2 之間相差 1).
解法
因為是一顆二叉搜索樹, 所以採用中序遍歷可以得到所有值從小到大的排列, 那麼將每個節點與上個節點的值 prev 進行比較得出相差值 answer, 判斷相差值與上個相差值, 將更小的存起來. 直到遍歷完整棵樹.
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { private int prev = -1; private int answer = Integer.MAX_VALUE; public int getMinimumDifference(TreeNode root) { if (root.left != null) { getMinimumDifference(root.left); } if (prev != -1) { answer = Math.min(answer, root.val - prev); } prev = root.val; if (root.right != null) { getMinimumDifference(root.right); } return answer; } }Runtime: 1 ms, faster than 95.95% of Java online submissions for Minimum Absolute Difference in BST. Memory Usage: 38.4 MB, less than 97.37% of Java online submissions for Minimum Absolute Difference in BST.