-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy path450.delete-node-in-a-bst.py
82 lines (72 loc) · 2.56 KB
/
450.delete-node-in-a-bst.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#
# @lc app=leetcode id=450 lang=python3
#
# [450] Delete Node in a BST
#
# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
# TAGS: Binary Search Tree, 2 ways
# REVIEWME:
class Solution:
# 112 ms, 9.9%. Time and Space O(H)
def deleteNode(self, root: TreeNode, key: int) -> TreeNode:
def get_max(node: TreeNode) -> int:
while node and node.right:
node = node.right
return node.val
def pop_max(node: TreeNode) -> None:
if not node: return None
if node.right:
node.right = pop_max(node.right)
else:
return node.left
return node
def delete(node, value) -> TreeNode:
if not node: return None
if value > node.val:
node.right = delete(node.right, value)
elif value < node.val:
node.left = delete(node.left, value)
else:
if node.left and node.right:
node.val = get_max(node.left)
node.left = pop_max(node.left)
else:
return node.left or node.right
return node
return delete(root, key)
# 96 ms, 12.42%. Time and Space O(H)
def deleteNode(self, root: TreeNode, key: int) -> TreeNode:
def get_max_left(node: TreeNode) -> int:
node = node.left
while node and node.right:
node = node.right
return node.val
def get_min_right(node: TreeNode) -> None:
node = node.right
while node and node.left:
node = node.left
return node.val
def delete(node, value) -> TreeNode:
if not node: return None
if value > node.val:
node.right = delete(node.right, value)
elif value < node.val:
node.left = delete(node.left, value)
else:
if node.left is node.right is None:
return None
if node.left:
node.val = get_max_left(node)
node.left = delete(node.left, node.val)
else:
node.val = get_min_right(node)
node.right = delete(node.right, node.val)
return node
return delete(root, key)
# @lc code=end