代码随想录Day23打卡 二叉树(8)

28 阅读1分钟

669 修剪二叉搜索树

注意在root值超出【low,high】的情况

var trimBST = function(root, low, high) {
    // base case: if root is null, return null
    if (!root) {
        return null
    }
    // if root.val is smaller than low, we should also consider root's right subtree 
    if (root.val < low) {
        return trimBST(root.right, low, high)
    } else if (root.val > high) {
    // if root.val is greater than high, we can then consider the root's left subtree
        return trimBST(root.left, low, high)
    } else {
        // otherwise, return root with left and right subtree being trimmed
        root.left = trimBST(root.left, low, high)
        root.right = trimBST(root.right, low, high)
        return root
    }
};

108 将有序数组转为二叉树

可以通过pass index优化

var sortedArrayToBST = function(nums) {
    return build(nums)
};

const build = (nums) => {
    if (nums.length === 0) {
        return null
    }
    const mid = Math.floor(nums.length / 2)
    const root = new TreeNode(nums[mid])
    root.left = build(nums.slice(0, mid))
    root.right = build(nums.slice(mid + 1, nums.length))
    return root
}

538 把二叉搜索树转换为累加树

反向中序遍历

var convertBST = function(root) {
    let pre = 0
    const traverse = (node) => {
        if (!node) {
            return 
        }
        traverse(node.right)
        pre += node.val
        node.val = pre
        traverse(node.left)
    }
    traverse(root)
    return root
};