打卡-算法训练营-Day18 | 530. 二叉搜索树的最小绝对差;501. 二叉搜索树中的众数;236. 二叉树的最近公共祖先

65 阅读1分钟

二叉搜索树的最小绝对差

leetcode链接:leetcode.cn/problems/mi…

简单题,使用二叉搜索的双指针遍历,记录最小的差值

var getMinimumDifference = function(root) {
    let min = Infinity;
    let pre = null;
    
    let dfs = (node) => {
        if (!node) return;
        dfs(node.left);
        if (pre && (node.val - pre.val) < min) {
            min = node.val - pre.val;
        }
        pre = node;
        dfs(node.right);
    }
    dfs(root);
    return min;
};

二叉搜索树中的众数

leetcode链接:leetcode.cn/problems/fi…

复杂点的方法可以使用map记录二叉树中每个元素出现的频率,然后统计map中出现次数最高的元素

简单点的方法就是利用二叉搜索树的中序遍历是递增的这个特性来统计出现的最大频率和节点的值

var findMode = function(root) {
    let result = [];
    let count = 0;
    let maxCount = 0;
    let pre = null;

    let dfs = (node) => {
        if (!node) return;

        dfs(node.left); // 左

        // 中
        if (pre === null) {
            count = 1;
        } else if (pre.val === node.val) {
            count++;
        } else {
            count = 1;
        }
        pre = node;

        // 更新maxCount和result
        if (maxCount === count) {
            result.push(node.val);
        }
        if (maxCount < count) {
            maxCount = count;
            result = [node.val]; // 清空数组,放入新节点的值
        }

        dfs(node.right) // 右
    }
    dfs(root);
    return result;
};

二叉树的最近公共祖先

leetcode链接:leetcode.cn/problems/lo…

这道题目使用后序遍历,先找到p和q节点,然后往上遍历找到最近的公共祖先

需要额外考虑p或q节点就是最近公共祖先的情况

var lowestCommonAncestor = function(root, p, q) {
    if (!root) return null;
    if (root === p || root === q) return root;

    let left = lowestCommonAncestor(root.left, p, q); // 左
    let right = lowestCommonAncestor(root.right, p, q); // 右

    // 中
    if (left && right) {
        return root;
    } else if (left === null && right) {
        return right;
    } else if (left && right === null) {
        return left;
    } else {
        return null;
    }
};