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

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

1)通过中序遍历来记录前一个节点与当前节点的绝对差

class Solution {
    int min = Integer.MAX_VALUE;
    TreeNode pre = null;

    public int getMinimumDifference(TreeNode root) {

         tranverse(root);
         return min;
    }

    public void tranverse(TreeNode root) {
        if (root == null) {
            return;
        }

        tranverse(root.left);

        //find the min absolute diffirence at here
        if (pre != null) {
            min = Math.min(min, Math.abs(root.val - pre.val));
        }
        pre = root;

        tranverse(root.right);
    }
}

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

1)通过中序遍历来找众数,因为是递增序列,如果有相同的会在一起

2)在写查找众数时,先判断当前节点的值和之前记录的值是否相等,相等 count = count + 1; 否则count = 1;

3) 在比较当前的count和maxCount, 如果相等,就加入到arraylist里;不相等说明要更新众数,清楚list之前的众数,添加新的众数。

class Solution {
    int currCount = 0;
    int maxCount = 0;
    int currentVal;

    List<Integer> res = new ArrayList<>();

    public int[] findMode(TreeNode root) {
        tranverse(root);

        int[] result = new int[res.size()];

        for (int i = 0; i < res.size(); i++) {
            result[i] = res.get(i);
        }
        return result;
    }

    public void tranverse(TreeNode node) {
        if (node == null) {
            return;
        }

        tranverse(node.left);

        currCount = (node.val == currentVal) ? currCount + 1 : 1 ;

            if (currCount == maxCount) {
                res.add(node.val);

            } else if (currCount > maxCount) {
                res.clear();
                maxCount = currCount;
                res.add(node.val);
            }

        currentVal = node.val;
        tranverse(node.right);
    }
}

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

1)两个节点的最近公共祖先其实就是这两个节点向根节点的 ‘ 延长线 ’ 的交汇点

2)如果一个节点能够在它的左右子树中分别找到 p 和 q,则该节点为 LCA 节点,也包括该节点自身


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

        if (root.val == p.val || root.val == q.val) {
            return root;
        }

        TreeNode left = lowestCommonAncestor(root.left, p, q);
        TreeNode right = lowestCommonAncestor(root.right, p, q);

        if (left != null && right != null) {
            return root;
        } 

        return (left != null) ? left : right;

    }



}

  • 8
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值