Skip to content

Commit 5eb6ff4

Browse files
committedDec 22, 2020
feat: delete-node-in-a-bst
1 parent 0e1c019 commit 5eb6ff4

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed
 

‎bst.delete-node-in-a-bst.py

+61
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
# Definition for a binary tree node.
2+
class TreeNode:
3+
def __init__(self, val=0, left=None, right=None):
4+
self.val = val
5+
self.left = left
6+
self.right = right
7+
8+
class Solution:
9+
"""
10+
450. 删除二叉搜索树中的节点
11+
https://leetcode-cn.com/problems/delete-node-in-a-bst/
12+
https://www.geekxh.com/1.4.%E4%BA%8C%E5%8F%89%E6%A0%91%E7%B3%BB%E5%88%97/405.html#_04%E3%80%81go%E8%AF%AD%E8%A8%80%E7%A4%BA%E4%BE%8B
13+
给定一个二叉搜索树的根节点 root 和一个值 key,删除二叉搜索树中的 key 对应的节点,并保证二叉搜索树的性质不变。返回二叉搜索树(有可能被更新)的根节点的引用。
14+
一般来说,删除节点可分为两个步骤:
15+
- 首先找到需要删除的节点;
16+
- 如果找到了,删除它。
17+
- 说明:要求算法时间复杂度为 O(h),h 为树的高度。
18+
"""
19+
def deleteNode(self, root: TreeNode, key: int) -> TreeNode:
20+
if not root:
21+
return None
22+
23+
if key < root.val:
24+
root.left = self.deleteNode(root.left, key)
25+
return root
26+
27+
if key > root.val:
28+
root.right = self.deleteNode(root.right, key)
29+
return root
30+
31+
# 当走到这里的时候,代表已经找到 root
32+
# 如果右子树为空,则用左子树代替自己
33+
if not root.right:
34+
return root.left
35+
36+
# 如果左子树为空,则用右子树代替自己
37+
if not root.left:
38+
return root.right
39+
40+
# 如果左右子树都不为空,则找到比当前节点大的右侧最小节点
41+
min_node = root.right
42+
43+
while min_node.left:
44+
min_node = min_node.left
45+
46+
root.val = min_node.val
47+
# 右侧节点需要删除最小的元素
48+
root.right = self.deleteMinNode(root.right)
49+
return root
50+
51+
# 删除最小节点
52+
def deleteMinNode(self, root):
53+
# 如果当前节点没有左子节点,则直接返回右子节点
54+
if not root.left:
55+
p_right = root.right
56+
root.right = None
57+
return p_right
58+
59+
# 删除左侧的最小子节点
60+
root.left = self.deleteMinNode(root.left)
61+
return root

0 commit comments

Comments
 (0)