每日一题:783. 二叉搜索树节点最小距离

解题思路

两种解法,但是大致思路相同
第一种是dfs将每个点的值加入到一个list中,然后对list进行排序,再找出最小差值
第二种是bfs将每个点的值加入到一个list中,然后对list进行排序,再找出最小差值

代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    List<Integer> list = new ArrayList<>();
    public int minDiffInBST(TreeNode root) {
        dfs(root);
        Collections.sort(list);
        int min = Integer.MAX_VALUE;
        for (int i=0;i<list.size()-1;i++){
            min=Math.min(min,list.get(i+1)-list.get(i));
        }
        return min;
    }
    public void dfs(TreeNode node){
        if (node==null) return;
        list.add(node.val);
        if (node.right!=null) dfs(node.right);
        if (node.left!=null) dfs(node.left);
    }
}


class Solution {
    public int minDiffInBST(TreeNode root) {
        LinkedList<TreeNode> queue = new LinkedList<>();
        List<Integer> list = new ArrayList<>();
        if (root==null) return 0;
        queue.add(root);
        int min = Integer.MAX_VALUE;
        while (!queue.isEmpty()){
            int n = queue.size();
            for (int i=0;i<n;i++){
                TreeNode node = queue.getFirst();
                queue.removeFirst();
                list.add(node.val);
                if (node.right!=null) queue.add(node.right);
                if (node.left!=null) queue.add(node.left);
            }
        }
        Collections.sort(list);
        for (int i=0;i<list.size()-1;i++){
            min=Math.min(min,list.get(i+1)-list.get(i));
        }
        return min;

    }
}

你可能感兴趣的:(DFS,BFS,leetcode,算法)