代码随想录算法训练营第十八天| 235.二叉搜索树的最近公共祖先、701.二叉搜索树中的插入操作、450. 删除二叉搜索树中的节点

题目链接:235. 二叉搜索树的最近公共祖先 - 力扣(LeetCode)

class Solution(object):

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

        if root == None:
            return root

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

        return root

题目链接:701. 二叉搜索树中的插入操作 - 力扣(LeetCode)

思路:很简单,val比当前节点大,往右找,val比当前节点小,往左找;直到找到None,并记录pre,再插入。

class Solution(object):
    def insertIntoBST(self, root, val):
        """
        :type root: TreeNode
        :type val: int
        :rtype: TreeNode
        """

        index = root
        pre = None
        while index != None:

            pre = index

            if val > index.val:
                index = index.right
            else:
                index = index.left

        if pre == None:
            return TreeNode(val)

        if pre.val > val:
            pre.left = TreeNode(val)
        else:
            pre.right = TreeNode(val)

        return root

题目链接:450. 删除二叉搜索树中的节点 - 力扣(LeetCode)

第一次用迭代没做出来,思路是正确的,但是处理不好;看了代码随想录写出的答案

class Solution:
    def deleteNode(self, root, key):
        if root is None:
            return root
        if root.val == key:
            if root.left is None and root.right is None:
                return None
            elif root.left is None:
                return root.right
            elif root.right is None:
                return root.left
            else:
                cur = root.right
                while cur.left is not None:
                    cur = cur.left
                cur.left = root.left
                return root.right
        if root.val > key:
            root.left = self.deleteNode(root.left, key)
        if root.val < key:
            root.right = self.deleteNode(root.right, key)
        return root
        

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值