代码随想录Day20打卡 二叉树(6)

57 阅读1分钟

654 最大二叉树

构造树,先构造root节点,再构建左右子树

var constructMaximumBinaryTree = function (nums) {
    if (nums.length === 0) {
        return null
    }
    // find the maximum
    let index = 0
    let max = nums[0]
    for (let i = 0; i < nums.length; i++) {
        if (nums[i] > max) {
            index = i
            max = nums[i]
        }
    }
    const root = new TreeNode(max)
    root.left = constructMaximumBinaryTree(nums.slice(0, index))
    root.right = constructMaximumBinaryTree(nums.slice(index + 1, nums.length))
    return root
};

617 合并二叉树

var mergeTrees = function(root1, root2) {
    if (root1 === null && root2 === null) {
        return null
    }
    if (root1 === null) {
        return root2
    }
    if (root2 === null) {
        return root1
    }
    const node = new TreeNode(root1.val + root2.val)
    node.left = mergeTrees(root1.left, root2.left)
    node.right = mergeTrees(root1.right, root2.right)
    return node
};

700 二叉树中的搜索

利用二叉搜索树的特性

var searchBST = function(root, val) {
    if (!root) {
        return null
    }
    if (root.val === val) {
        return root
    }
    if (root.val > val) {
        return searchBST(root.left, val)
    }
    if (root.val < val) {
        return searchBST(root.right, val)
    }
    return
};

98 验证二叉搜索树

记录一个max和min值,在遍历的同时维护这两个值的更新

var isValidBST = function(root) {
    let max = Infinity, min = -Infinity
    const dfs = (node, maxVal, minVal) => {
        if (!node) {
            return true
        }
        if (node.val >= maxVal || node.val <= minVal) {
            return false
        }
        return dfs(node.left, node.val, minVal) && dfs(node.right, maxVal, node.val)
    }
    return dfs(root, max, min)
};