nlogn without using any data structure

  • 0
    public int getMinimumDifference(TreeNode root) {
        int min = getMinimumDifferenceSub(root);
        if(root.left != null)
            min = Math.min(min, getMinimumDifference(root.left));
        if(root.right != null)
            min = Math.min(min, getMinimumDifference(root.right));
        return min;
    private int getMinimumDifferenceSub(TreeNode root){
        int min = Integer.MAX_VALUE;
        if(root.left != null){
            TreeNode t = root.left;
            while(t.right != null)
                t = t.right;
            min = Math.min(min, Math.abs(t.val - root.val));
        if(root.right != null){
            TreeNode t = root.right;
            while(t.left != null)
                t = t.left;
            min = Math.min(min, Math.abs(t.val - root.val));
        return min;

    getMinimumDifferenceSub(): computes the min diff containing root;
    getMinimumDifference();computes the min diff not containing root;
    I think this idea is similar to pathSum(3)

Log in to reply

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