前端算法系列-二叉树08

43 阅读1分钟

669. 修剪二叉搜索树

var trimBST = function(root, low, high) {
    if(!root) return null
    if(root.val > high){
        if(!root.left && !root.right){
            return null
        }else if(!root.left && root.right){
            return null
        }else{
            return trimBST(root.left,low,high)
        }
    }else if(root.val < low){
        if(!root.left && !root.right){
            return null
        }else if(root.left && !root.right){
            return null
        }else{
            return trimBST(root.right,low,high)
        }
    }
    return new TreeNode(root.val,trimBST(root.left,low,high),trimBST(root.right,low,high))
};

108. 将有序数组转换为二叉搜索树

var sortedArrayToBST = function (nums) {
    const buildTree = (Arr, left, right) => {
        if (left > right)
            return null;

        let mid = Math.floor(left + (right - left) / 2);

        let root = new TreeNode(Arr[mid]);
        root.left = buildTree(Arr, left, mid - 1);
        root.right = buildTree(Arr, mid + 1, right);
        return root;
    }
    return buildTree(nums, 0, nums.length - 1);
};

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

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