Programming Camp – Algorithm Training Camp – Day 22

1. Lowest Common Ancestor of a Binary Search Tree (Leetcode Number: 235)

The solution of 236 works here as well. The following solution is only for BST due to its feature.

class Solution:
    def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
        
        if root.val < p.val and root.val < q.val:
            return self.lowestCommonAncestor(root.right, p, q)
        if root.val > p.val and root.val > q.val:
            return self.lowestCommonAncestor(root.left, p, q)
        return root

2. Insert into a Binary Search Tree (Leetcode Number: 701)

Highlight the feature of BST and design the traversal strategy accordingly would save time on searching!

Write the termination condition on top of the function!

class Solution:
    def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
        
        if not root:
            return TreeNode(val)
        
        if root.val < val:
            root.right = self.insertIntoBST(root.right, val)
            
        if root.val > val:
            root.left = self.insertIntoBST(root.left, val)
        
        return root

3. Delete Node in a BST (Leetcode Number: 450)

Got stuck at the while function

class Solution:
    def deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]:
        if not root:
            return None
        
        if root.val < key:
                root.right = self.deleteNode(root.right, key)
        elif root.val > key:
                root.left = self.deleteNode(root.left, key)
        else:
            if not root.left:
                return root.right
            if not root.right:
                return root.left
            
            # Replacement strategy for the nodes that have both left child and right child
            node = root.right
            
            while node.left:
                node = node.left
                
            node.left = root.left
            root = root.right
            
        return root

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值