代码随想录刷题第二十二天 |235. 二叉搜索树的最近公共祖先 ● 701.二叉搜索树中的插入操作 ● 450.删除二叉搜索树中的节点

代码随想录刷题第二十二天

二叉搜索树的最近公共祖先 (LC 235) 简单

题目思路:

在这里插入图片描述

代码实现:

class Solution(object):
    def lowestCommonAncestor(self, root, p, q):
        """
        :type root: TreeNode
        :type p: TreeNode
        :type q: TreeNode
        :rtype: TreeNode
        """

        if root is None:
            return None
            
        if root.val < p.val and root.val < q.val:
            left = self.lowestCommonAncestor(root.right, p, q)
            if left is not None:
                return left
        
        elif root.val > q.val and root.val > p.val:
            right = self.lowestCommonAncestor(root.left, p, q)
            if right is not None:
                return right
        
        else:
            return root

二叉搜索树的插入操作 (LC 701) 简单

题目思路:

在这里插入图片描述

代码实现:

class Solution(object):
    def insertIntoBST(self, root, val):
        """
        :type root: TreeNode
        :type val: int
        :rtype: TreeNode
        """
        if root is None:
            newnode = TreeNode(val)
            return newnode

        if root.val > val:
            root.left = self.insertIntoBST(root.left, val)

        if root.val < val:
            root.right = self.insertIntoBST(root.right, val)

        return root

删除二叉搜索树中的节点 (LC 450) 困难

题目思路:

在这里插入图片描述

代码实现:

class Solution(object):
    def deleteNode(self, root, key):
        """
        :type root: TreeNode
        :type key: int
        :rtype: TreeNode
        """
        if root is None:
            return None
        
        if root.val == key:
            if root.left is None and root.right is None:
                return None
            elif root.left is not None and root.right is None:
                return root.left
            elif root.left is None and root.right is not None:
                return root.right
            else:
                return self.constructsubtree(root.right, root.left)
        else:
            root.left = self.deleteNode(root.left, key)
            root.right = self.deleteNode(root.right, key)

        return root

    
    def constructsubtree(self, rightroot, leftroot):
        if rightroot is None:
            return leftroot
        
        rightroot.left = self.constructsubtree(rightroot.left, leftroot)
        return rightroot
  • 7
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值