代码随想录Day21打卡 二叉树(7)

61 阅读1分钟

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

中序遍历得到有序数组,之后求出差值

var getMinimumDifference = function (root) {
    const order = []
    const dfs = (node) => {
        if (!node) {
            return
        }
        dfs(node.left)
        order.push(node.val)
        dfs(node.right)
    }
    dfs(root)
    let res = Infinity
    for (let i = 1; i < order.length; i++) {
        res = Math.min(order[i] - order[i-1], res)
    }
    return res
};

pre指针做法

var getMinimumDifference = function (root) {
    let res = Infinity
    // 因为第一个数字没有pre,所以我们要有pre = null
    let pre = null
    const inorder = (node) => {
        if (!node) return
        inorder(node.left)
        if (pre) {
            res = Math.min(res, node.val - pre.val)
        }
        // 注意要在中序的时候更新pre
        pre = node
        inorder(node.right)
    }
    inorder(root)
    return res
};

501 二叉搜索树中的众树

var findMode = function (root) {
    let cnt = 0, max = 1
    // 为了防止只有root的情况,pre最开始为root
    let pre = root, res = []

    const dfs = (node) => {
        if (!node) {
            return
        }
        dfs(node.left)
        if (pre) {
            if (pre.val === node.val) {
                cnt += 1
            } else {
                cnt = 1
            }
        }
        pre = node
        if (cnt === max) {
            res.push(node.val)
        }
        if (cnt > max) {
            max = cnt
            res = []
            res.push(node.val)
        }
        dfs(node.right)
    }

    dfs(root)
    return res
};

236 二叉树的最近公共祖先

var lowestCommonAncestor = function(root, p, q) {
    if (!root) {
        return null
    }
    if (root === p || root === q) {
        return root
    }
    const left = lowestCommonAncestor(root.left, p, q)
    const right = lowestCommonAncestor(root.right, p, q)
    if (!left && !right) {
        return null
    }
    if (left && right) {
        return root
    }
    if (left) {
        return left
    }
    if (right) {
        return right
    }
};