代码随想录第21天: 二叉树part07

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

class Solution {
    List<Integer> inorderList = new ArrayList<>();

    public void inorder(TreeNode root) {
        if(root == null) return;
        if(root.left != null) inorder(root.left);
        inorderList.add(root.val);
        if(root.right != null) inorder(root.right);
    }

    public int getMinimumDifference(TreeNode root) {
        inorder(root);
        int minValue = Integer.MAX_VALUE;
        for(int i = inorderList.size() - 1; i > 0; i--) {
            int value = inorderList.get(i) - inorderList.get(i - 1);
            if(value < minValue) {
                minValue = value;
            }
        }
        return minValue;
    }
}

力扣501.二叉搜索树中的众数

class Solution {
    TreeNode pre = new TreeNode();
    List<Integer> resList = new ArrayList<>();
    int count;
    int maxCount;

    public int[] findMode(TreeNode root) {
        pre = null;
        count = 0;
        maxCount = 0;
        inorder(root);
        int[] resArray = new int[resList.size()];
        for (int i = 0; i < resList.size(); i++) {
            resArray[i] = resList.get(i);
        }
        return resArray;
    }

    public void inorder(TreeNode root) {
        if (root == null)
            return;
        if (root.left != null)
            inorder(root.left);
        if (pre == null || pre.val != root.val)
            count = 1;
        else
            count++;
        if (count > maxCount) {
            resList.clear();
            maxCount = count;
            resList.add(root.val);
        } else if (count == maxCount) {
            resList.add(root.val);
        }
        pre = root;
        if (root.right != null)
            inorder(root.right);
    }
}

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

class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root == null) return null;
        if(root == p || root == q) return root;
        TreeNode left = lowestCommonAncestor(root.left, p, q);
        TreeNode right = lowestCommonAncestor(root.right, p, q);
        if(left == null && right == null) return null;
        else if(left != null && right == null) return left;
        else if(left == null && right != null) return right;
        return root;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值