Skip to content

Commit e7c0fe7

Browse files
author
Partho Biswas
committed
leetcode 450. Delete Node in a BST
1 parent 6b91568 commit e7c0fe7

File tree

2 files changed

+36
-1
lines changed

2 files changed

+36
-1
lines changed

algoexpert.io/python/BST_Construction_Iterative.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ def remove(self, value, parentNode=None):
4747
parentNode = currentNode
4848
currentNode = currentNode.left
4949
elif value > currentNode.value:
50-
parentNode = currentNode
50+
paretNode = currentNode
5151
currentNode = currentNode.right
5252
else:
5353
if currentNode.left is not None and currentNode.right is not None:

leetcode.com/python/#450 - Delete Node in a BST.py

+35
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
# https://leetcode.com/problems/delete-node-in-a-bst/solution/
2+
13
# Definition for a binary tree node.
24
# class TreeNode(object):
35
# def __init__(self, x):
@@ -6,9 +8,42 @@
68
# self.right = None
79

810
class Solution(object):
11+
12+
def successor(self, root):
13+
root = root.right
14+
while root.left:
15+
root = root.left
16+
return root.val
17+
18+
def predecessor(self, root):
19+
root = root.left
20+
while root.right:
21+
root = root.right
22+
return root.val
23+
924
def deleteNode(self, root, key):
1025
"""
1126
:type root: TreeNode
1227
:type key: int
1328
:rtype: TreeNode
1429
"""
30+
if root is None:
31+
return None
32+
if key < root.val:
33+
root.left = self.deleteNode(root.left, key)
34+
elif key > root.val:
35+
root.right = self.deleteNode(root.right, key)
36+
else:
37+
if root.left is None and root.right is None:
38+
root = None
39+
elif root.right is not None:
40+
succrssor = self.successor(root)
41+
root.val = succrssor
42+
root.right = self.deleteNode(root.right, succrssor)
43+
elif root.left is not None:
44+
predecessor = self.predecessor(root)
45+
root.val = predecessor
46+
root.left = self.deleteNode(root.left, predecessor)
47+
return root
48+
49+

0 commit comments

Comments
 (0)