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

本文详细介绍了二叉树中最近公共祖先、插入及删除节点的操作方法。针对最近公共祖先问题,提供了递归与迭代两种解决方案;对于插入节点,探讨了递归与迭代的不同实现方式;在删除节点方面,则全面分析了五种不同情况下的处理策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

235. Lowest Common Ancestor of a Binary Search Tree

求二叉树最近公共祖先的方法

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
        if root == None: return None
        if root == p or root == q: return root

        left = self.lowestCommonAncestor(root.left, p, q)
        right = self.lowestCommonAncestor(root.right, p, q)

        if left and right:
            return root

        if left != None and right == None:
            return left
        if left == None and right != None:
            return right

        if left != None and right != None:
            return None

利用二叉搜索树性质递归

节点的值介于p和q之间就是最近公共祖先

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def traversal(self, cur, p, q):
        if cur == None:
            return None

        if cur.val > p.val and cur.val > q.val:     # 左
            return self.traversal(cur.left, p, q)
        elif cur.val < p.val and cur.val < q.val:   # 右
            return self.traversal(cur.right, p, q)
        else:
            return cur                              # cur节点在区间,就是最近公共祖先

    def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':
        return self.traversal(root, p, q)
        

迭代

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

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

701. Insert into a Binary Search Tree

递归

插入为叶子节点,不改变树的结构

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
        # 插入为叶子节点,不改变树的结构
        # 终止条件
        if root == 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

迭代

双指针,记录父节点

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def insertIntoBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
        if root == None:
            return TreeNode(val)

        parent = root
        cur = root
        while cur:
            parent = cur    # 记录父节点
            if cur.val < val:
                cur = cur.right
            else:
                cur = cur.left
        # 此时cur位于停添加的位置
        newNode = TreeNode(val)
        if val < parent.val:
            parent.left = newNode
        else:
            parent.right = newNode

        return root
        

450. Delete Node in a BST

共有5种情况要考虑

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]:
        # 终止条件
        if root == None:    # 第一种情况:没找到删除的节点,遍历到空节点直接返回了
            return root
        
        if root.val == key:
            # 第二种情况:左右孩子都为空(叶子节点),直接删除节点, 返回NULL为根节点
            if root.left == None and root.right == None:
                return None 
            # 第三种情况:其左孩子为空,右孩子不为空,删除节点,右孩子补位 ,返回右孩子为根节点
            elif root.left == None and root.right != None:
                return root.right
            # 第四种情况:其右孩子为空,左孩子不为空,删除节点,左孩子补位,返回左孩子为根节点
            elif root.left != None and root.right == None:
                return root.left
            # 第五种情况:左右孩子节点都不为空,则将删除节点的左子树放到删除节点的右子树的最左面节点的左孩子的位置
            else:
                # 找到删除节点的右子树的最左面节点
                cur = root.right
                while cur.left != 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、付费专栏及课程。

余额充值