450. Delete Node in a BST

Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return the root node reference (possibly updated) of the BST.

Basically, the deletion can be divided into two stages:

Search for a node to remove.
If the node is found, delete the node.
Note: Time complexity should be O(height of tree).

Example:


image.png

还有bug

class Solution(object):
    def deleteNode(self, root, key):
        """
        :type root: TreeNode
        :type key: int
        :rtype: TreeNode
        """
        if not root: return root
        if key<root.val: 
            root.left = self.deleteNode(root.left, key)
            return root
        elif key>root.val: 
            root.right = self.deleteNode(root.right, key)
            return root
        else:
            if not root.left: return root.right
            elif not root.left.right: 
                root.left.right = root.right
                return root.left
            else:
                pre, lm = root.left, root.left.right
                while lm and lm.right: pre, lm=lm, lm.right
                pre.right = None
                lm.left = root.left
                lm.right = root.right
                return lm 
                
        
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Given a root node reference of a BST and a key, delete th...
    matrxyz阅读 397评论 0 0
  • 题目450. Delete Node in a BST Given a root node reference o...
    evil_ice阅读 380评论 0 0
  • Given a root node reference of a BST and a key, delete th...
    Jeanz阅读 263评论 0 0
  • “人言落日是天涯,望极天涯不见家。已恨碧山相阻隔,碧山还被暮云遮。”千年前暮春的一个傍晚,江西南城人李觏于...
    雨后嘉茗阅读 3,125评论 18 7
  • 深夜,我躺在床上,一天的疲累在此刻烟消云散……静静地听着歌,静静地思考着生活。 心智的渐渐成熟,少了情绪的波动,多...
    XUMIAO阅读 138评论 0 0