代码随想录算法训练营第21天|530.二叉搜索树的最小绝对差  ●  501.二叉搜索树中的众数  ●  236. 二叉树的最近公共祖先

50 阅读1分钟

今日内容 

●  530.二叉搜索树的最小绝对差 

●  501.二叉搜索树中的众数 

●  236. 二叉树的最近公共祖先

530. 二叉搜索树的最小绝对差

中序遍历

class Solution {
    //中序遍历
    TreeNode pre;
    int res = Integer.MAX_VALUE;

    public int getMinimumDifference(TreeNode root) {
        inOrder(root);
        return res;
    }
    private void inOrder(TreeNode root) {
        if(root == null)return;
        inOrder(root.left);
        if(pre != null) {
        res = Math.min(res, Math.abs(root.val - pre.val));
        }
        pre = root;
        inOrder(root.right);
    }
}

501. 二叉搜索树中的众数

class Solution {
    int count = 0;
    int maxCount = Integer.MIN_VALUE;
    List<Integer> res;
    TreeNode pre = null;
    public int[] findMode(TreeNode root) {
        res = new ArrayList<>();
        dfs(root);
        int size = res.size();
        int[] resArr = new int[size];
        for(int i = 0; i < size; i++) {
            resArr[i] = res.get(i);
        }
        return resArr;
    }
    private void dfs(TreeNode root) {
        if(root == null)return;
        dfs(root.left);
        if(pre != null && pre.val == root.val) {
            count++;
        } else {
            count = 1;
        }
        if(count == maxCount) {
            res.add(root.val);
        } else if(count > maxCount) {
            maxCount = count;
            res.clear();
            res.add(root.val);
        }
        pre = root;
        dfs(root.right);
    }
}

236. 二叉树的最近公共祖先

主要是整棵树都要进行后序遍历,不能在中间中断

class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root == null || root == p || root == q)return root;
        TreeNode left = lowestCommonAncestor(root.left, p, q);
        TreeNode right = lowestCommonAncestor(root.right, p, q);
        if(left == null)return right;
        if(right == null)return left;
        return root;
    }
}