1. 程式人生 > >450. 刪除二叉搜尋樹中的節點(中等、二叉搜尋樹)

450. 刪除二叉搜尋樹中的節點(中等、二叉搜尋樹)

 給定一個二叉搜尋樹的根節點 root 和一個值 key,刪除二叉搜尋樹中的 key 對應的節點,並保證二叉搜尋樹的性質不變。返回二叉搜尋樹(有可能被更新)的根節點的引用。

一般來說,刪除節點可分為兩個步驟:

  1. 首先找到需要刪除的節點;
  2. 如果找到了,刪除它。

示例:

root = [5,3,6,2,4,null,7]
key = 3

    5
   / \
  3   6
 / \   \
2   4   7

給定需要刪除的節點值是 3,所以我們首先找到 3 這個節點,然後刪除它。

一個正確的答案是 [5,4,6,2,null,null,7], 如下圖所示。

    5
   / \
  4   6
 /     \
2       7

另一個正確答案是 [5,2,6,null,4,null,7]。

    5
   / \
  2   6
   \   \
    4   7
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def deleteNode(self, root, key):
        """
        :type root: TreeNode
        :type key: int
        :rtype: TreeNode
        """
        if not root:
            return None
        if root.val==key:
            if not root.right:
                return root.left
            else:
                #root.val=None
                dummy=root.right
                while dummy.left:
                    dummy=dummy.left
                root.val,dummy.val=dummy.val, root.val
        root.left=self.deleteNode(root.left, key)
        root.right=self.deleteNode(root.right, key)
        return root

執行用時: 116 ms, 在Delete Node in a BST的Python3提交中擊敗了55.29% 的使用者