LeetCode 0450. Delete Node in a BST 刪除二叉搜索樹中的節點【Medium】【Python】【二叉樹】
Problem
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:
root = [5,3,6,2,4,null,7]
key = 3
5
/ \
3 6
/ \ \
2 4 7
Given key to delete is 3. So we find the node with value 3 and delete it.
One valid answer is [5,4,6,2,null,null,7], shown in the following BST.
5
/ \
4 6
/ \
2 7
Another valid answer is [5,2,6,null,4,null,7].
5
/ \
2 6
\ \
4 7
問題
給定一個二叉搜索樹的根節點 root 和一個值 key,刪除二叉搜索樹中的 key 對應的節點,並保證二叉搜索樹的性質不變。返回二叉搜索樹(有可能被更新)的根節點的引用。
一般來說,刪除節點可分爲兩個步驟:
- 首先找到需要刪除的節點;
- 如果找到了,刪除它。
說明: 要求算法時間複雜度爲 O(h),h 爲樹的高度。
示例:
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
思路
二叉樹
Python3代碼
# 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: TreeNode, key: int) -> TreeNode:
# 樹爲空
if root == None:
return None
# 找到 key,進行刪除
if root.val == key:
# 情況 1:兩個子節點都爲空
# 情況 2:只有一個非空子節點,讓這個孩子取代自己
if root.left == None:
return root.right
if root.right == None:
return root.left
# 情況 3:有兩個非空子節點,找到左子樹的最大值,或者右子樹的最小值,取代自己
# Python3 需要先有一個 TreeNode 對象
minNode = TreeNode(None)
minNode = self.getMin(root.right)
root.val = minNode.val
root.right = self.deleteNode(root.right, minNode.val)
# key 在左子樹
elif root.val > key:
root.left = self.deleteNode(root.left, key)
# key 在右子樹
elif root.val < key:
root.right = self.deleteNode(root.right, key)
return root
def getMin(self, node: TreeNode):
# BST 最左邊的是最小值
while node.left != None:
node = node.left
return node