Leetcode brushing questions-the minimum distance of binary search tree nodes

After writing such a question on Leetcode, I feel that my thinking is quite good, share it:

Idea: First, add each non-null node val to a set through depth-first search, and then traverse the set to find the minimum value of the difference.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {

    private int min = Integer.MAX_VALUE;

    public int minDiffInBST(TreeNode root) {
        List<Integer> valueList = new ArrayList<Integer>();
        dfs(root,valueList);
        for(int i = 0;i < valueList.size();i++){
            for(int j = i + 1;j < valueList.size();j++){
                min = Math.min(min,Math.abs(valueList.get(i)-valueList.get(j)));
            }
        }
        return min;
    }

    public void dfs(TreeNode node,List<Integer> list){
        if(node != null){
            int a = node.val;
            list.add(a);
            dfs(node.left,list);
            dfs(node.right,list);
        }
    }

}

But it is obvious: the double for loop greatly increases the time complexity!

 

Then, we should think about how to optimize:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {

    private int min = Integer.MAX_VALUE;

    public int minDiffInBST(TreeNode root) {
        List<Integer> valueList = new ArrayList<Integer>();
        dfs(root,valueList);
        /*for(int i = 0;i < valueList.size();i++){
            for(int j = i + 1;j < valueList.size();j++){
                min = Math.min(min,Math.abs(valueList.get(i)-valueList.get(j)));
            }
        }*/
        Collections.sort(valueList);
        for(int i = 0; i < valueList.size() - 1;i++){
            min = Math.min(min,valueList.get(i+1)-valueList.get(i));
        }
        return min;
    }

    public void dfs(TreeNode node,List<Integer> list){
        if(node != null){
            int a = node.val;
            list.add(a);
            dfs(node.left,list);
            dfs(node.right,list);
        }
    }

}

Let's take a look at the effect:

Guess you like

Origin blog.csdn.net/qq_36428821/article/details/113053052