Day19 | ● 235. 二叉搜索树的最近公共祖先 ● 701.二叉搜索树中的插入操作 ● 450.删除二叉搜索树中的节点

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

利用二叉搜索树的特性进行分析,先与根节点比较后盘点去左边还是右边。

func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode {
	if root == nil {return nil}

    maxval := int(math.Max(float64(p.Val), float64(q.Val)))
    minval := int(math.Min(float64(p.Val), float64(q.Val)))

    if maxval >= root.Val && minval <= root.Val {
        return root
    }
    var leftptr, rightptr *TreeNode

    if maxval < root.Val{
        leftptr = lowestCommonAncestor(root.Left, p, q)
    }
    if minval > root.Val{
        rightptr = lowestCommonAncestor(root.Right, p ,q)
    }
    if leftptr != nil{
        return leftptr
    }
    if rightptr != nil{
        return rightptr
    }
    return nil
}

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

可以插入到头节点,然后调整树,也可以插入到叶子节点。
插入头节点就是插入成功后可以直接返回头节点的地址,但是插入叶子节点的时候必须保留一下当前头节点的地址,要不然没有返回值。

func insertIntoBST(root *TreeNode, val int) *TreeNode {
    tmp := &TreeNode{Val : val}
    if root == nil{
        return tmp
    }
    Bottominsert(root, tmp, val)
    return root
}

func Bottominsert(node *TreeNode, ins *TreeNode, val int) {
    if node.Val > val{
        if node.Left == nil{
            node.Left = ins
        }else{
            Bottominsert(node.Left, ins, val)
        }
    }else{
        if node.Right == nil{
            node.Right = ins
        }else{
            Bottominsert(node.Right, ins, val)
        }
    }
}

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

代码感觉比较繁琐,其实就是找到了该节点且左右子树都不为空时,将右节点作为新的主节点,左节点挂在右节点的最左叶子节点上。


// 递归版本
func deleteNode(root *TreeNode, key int) *TreeNode {
    if root == nil {
        return nil
    }
    if key < root.Val {
        root.Left = deleteNode(root.Left, key)
        return root
    }
    if key > root.Val {
        root.Right = deleteNode(root.Right, key)
        return root
    }
    if root.Right == nil {
        return root.Left
    }
    if root.Left == nil{
        return root.Right
    }
    minnode := root.Right
    for minnode.Left != nil {
        minnode = minnode.Left
    }
    minnode.Left = root.Left
    root = root.Right
    //root.Val = minnode.Val
    //root.Right = deleteNode1(root.Right)
    return root
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值