Java O(N) Solution - Recursive


  • 0
    S

    class Solution {

    public int minAbsDiff(TreeNode root) {
    	
    	List<Integer> inOrder = new ArrayList<Integer>();
    	inOrder.addAll(minAbsDiffHelper(root));
    	
    	int min = Integer.MAX_VALUE;
    	for (int i = 0; i < inOrder.size(); i++) {
    		min = Math.min(min, inOrder.get(i+1) - inOrder.get(i));
    	}
    	
    	return min;
    }
    
    public List<Integer> minAbsDiffHelper(TreeNode root) {
    	
    	List<Integer> inOrder = new ArrayList<Integer>();
    	if(!(root.left == null)) { 
    		inOrder.addAll(minAbsDiffHelper(root.left));
    	}
    	inOrder.add(root.val);
    	if(!(root.right == null)) {
    		inOrder.addAll(minAbsDiffHelper(root.right));
    	}
    	return inOrder;
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.