payal-kothari
7/25/2017 - 11:30 PM

MUST READ ** inorder BST gives sorted list *** preorder(I think any traversal should work) and Treeset ** when it's not a BST Recursive ..

MUST READ ** inorder BST gives sorted list *** preorder(I think any traversal should work) and Treeset ** when it's not a BST Recursive .. must read!! Time Complexity - O(n) Space Complexity - O(1)

``````// The idea is to put values in a TreeSet and then every time we can use O(lgN) time to lookup for the nearest values.

// Solution 2 - Pre-Order traverse, time complexity O(NlgN), space complexity O(N).

public class Solution {
TreeSet<Integer> set = new TreeSet<>();
int min = Integer.MAX_VALUE;

public int getMinimumDifference(TreeNode root) {
if (root == null) return min;

if (!set.isEmpty()) {
if (set.floor(root.val) != null) {
min = Math.min(min, root.val - set.floor(root.val));
}
if (set.ceiling(root.val) != null) {
min = Math.min(min, set.ceiling(root.val) - root.val);
}
}

getMinimumDifference(root.left);
getMinimumDifference(root.right);

return min;
}
}``````
``````/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
public class Solution {
int min = Integer.MAX_VALUE;
Integer prev = null;

public int getMinimumDifference(TreeNode root) {
if (root == null){
return 0; // any int value is fine
}

getMinimumDifference(root.left);

if(prev != null){
min = Math.min(min, root.val - prev);
}
prev = root.val;

getMinimumDifference(root.right);

return min;
}

}``````