Minimum Absolute Difference in BST Solutions in Java
Number 530
Difficulty Easy
Acceptance 53.8%
Link LeetCode
Other languages —
Solutions
Java solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/minimum-absolute-difference-in-bst/description//// Author : liuyubobobo/// Time : 2018-04-30import java.util.ArrayList;import java.util.Collections;/// Traverse all nodes in BST and sort////// Time Complexity: O(nlogn)/// Space Complexity: O(n)class Solution {public int getMinimumDifference(TreeNode root) {ArrayList<Integer> list = new ArrayList<>();preOrder(root, list);Collections.sort(list);int res = Integer.MAX_VALUE;for(int i = 1 ; i < list.size() ; i ++)res = Math.min(res, list.get(i) - list.get(i - 1));return res;}private void preOrder(TreeNode node, ArrayList<Integer> list){if(node == null)return;list.add(node.val);preOrder(node.left, list);preOrder(node.right, list);}}
Java solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/minimum-absolute-difference-in-bst/description//// Author : liuyubobobo/// Time : 2018-04-30import java.util.ArrayList;import java.util.Collections;/// Using inorder to traverse all nodes////// Time Complexity: O(n)/// Space Complexity: O(n)class Solution2 {public int getMinimumDifference(TreeNode root) {ArrayList<Integer> list = new ArrayList<>();inOrder(root, list);int res = Integer.MAX_VALUE;for(int i = 1 ; i < list.size() ; i ++)res = Math.min(res, list.get(i) - list.get(i - 1));return res;}private void inOrder(TreeNode node, ArrayList<Integer> list){if(node == null)return;inOrder(node.left, list);list.add(node.val);inOrder(node.right, list);}}
Java solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/minimum-absolute-difference-in-bst/description//// Author : liuyubobobo/// Time : 2018-04-30import java.util.ArrayList;import java.util.Collections;/// Using inorder to traverse all nodes/// and calculates the result during the inorder traverse////// Time Complexity: O(n)/// Space Complexity: O(logn)class Solution3 {private Integer prev = null;public int getMinimumDifference(TreeNode root) {prev = null;return inOrder(root);}private int inOrder(TreeNode node){if(node == null)return Integer.MAX_VALUE;int res = Integer.MAX_VALUE;res = Math.min(res, inOrder(node.left));if(prev != null)res = Math.min(res, node.val - prev);prev = node.val;res = Math.min(res, inOrder(node.right));return res;}}