leetcode Day47 剑指专项 52-54

63 阅读1分钟

926. 将字符串翻转到单调递增

var minFlipsMonoIncr = function(s) {
    const n=s.length
    let dp0=0,dp1=0
    for(let i=0;i<n;i++){
        const c=s[i]
        let dp0new=dp0,dp1new=Math.min(dp0,dp1)
        if(c==='1'){
            dp0new++
        }else{
            dp1new++
        }
        dp0=dp0new
        dp1=dp1new
    }
    return Math.min(dp0,dp1)
};

剑指 Offer II 052. 展平二叉搜索树

var increasingBST = function(root) {
    let vals=getVals(root)
    let dummyNode=new TreeNode(-1)
    let cur=dummyNode
    for(let i of vals){
        cur.right=new TreeNode(i)
        cur=cur.right
    }
    return dummyNode.right
};
const getVals=(root)=>{
    let res=[]
    const dfs=(node)=>{
        if(!node){
            return 
        }
        dfs(node.left)
        res.push(node.val)
        dfs(node.right)
    }
    dfs(root)
    return res
}

剑指 Offer II 053. 二叉搜索树中的中序后继

var inorderSuccessor = function(root,p) {
    let cur=root
    let res=null
    while(cur){
        if(cur.val>p.val){
            res=cur
            cur=cur.left
        }else{
            cur=cur.right
        }
    }
    return res
}

剑指 Offer II 054. 所有大于等于节点的值之和

var convertBST = function(root) {
    let res=[]
    const dfs=(node)=>{
        if(!node){
            return 
        }
        dfs(node.right)
        res.push(node.val)
        node.val=getSum(res)
        dfs(node.left)
    }
    dfs(root)
    return root
};
const getSum=(arr)=>{
    return arr.reduce((a,b)=>a+b,0)
}