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 
                
        
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Given a root node reference of a BST and a key, delete th...
    matrxyz閱讀 429評論 0 0
  • 題目450. Delete Node in a BST Given a root node reference o...
    evil_ice閱讀 409評論 0 0
  • Given a root node reference of a BST and a key, delete th...
    Jeanz閱讀 302評論 0 0
  • “人言落日是天涯,望極天涯不見家。已恨碧山相阻隔,碧山還被暮云遮?!鼻昵澳捍旱囊粋€傍晚,江西南城人李覯于...
    雨后嘉茗閱讀 3,425評論 18 7
  • 深夜,我躺在床上,一天的疲累在此刻煙消云散……靜靜地聽著歌,靜靜地思考著生活。 心智的漸漸成熟,少了情緒的波動,多...
    XUMIAO閱讀 165評論 0 0

友情鏈接更多精彩內(nèi)容