前端算法系列-二叉树07

44 阅读1分钟

235. 二叉搜索树的最近公共祖先

var lowestCommonAncestor = function(root, p, q) {
    if(!root) return null
    if(root.val > p.val && root.val > q.val){
        let left = lowestCommonAncestor(root.left,p,q)
        if(left) return left
    }
    if(root.val < p.val && root.val < q.val){
        let right = lowestCommonAncestor(root.right,p,q)
        if(right) return right
    }
    return root
};

701. 二叉搜索树中的插入操作

var insertIntoBST = function(root, val) {
    let point = root
    while(point){
        if(val < point.val){
            if(!point.left){
                point.left = new TreeNode(val)
                point = null
            }else{
                point = point.left
            }
        }else{
            if(! point.right){
                point.right =  new TreeNode(val)
                point = null
            }else{
                point = point.right
            }

        }
    }
    return root ? root : new TreeNode(val)
};

450. 删除二叉搜索树中的节点

var deleteNode = function(root, key) {
    if(!root) return null
    if(root.val === key){
        // 左右节点都为空
        if(!root.left && !root.right){
            return null
        }else if(!root.left && root.right){
            // 左节点为空,右节点存在
            return root.right
        }else if(root.left && !root.right){
            // 左节点存在,右节点为空
            return root.left
        }else{
            // 左节点和右节点都存在
            // 把根节点的子孩子放在根节点右孩子的最左边,返回右孩子
            let insertPosition = root.right
            while(insertPosition.left){
                insertPosition = insertPosition.left
            }
            insertPosition.left = root.left
            return root.right
        }
    }
    return new TreeNode(root.val,deleteNode(root.left,key),deleteNode(root.right,key))
};