I tried to define a delete
function for a BST, and have run into some trouble.
There are insert
, find_max
, search
, preorder
, and delete
functions in this Solution
class. I expected to delete elements by using these function and test the result by deleting node = 3, 8, 21 then print the output.
However, I found that there is no output returned and the value of BS Tree are not same as I have expected, which is this expect outcome:
I wonder that this trouble might because some None
value.
Below are the input value:
root = None
s = Solution()
# 放入資料
root = s.insert(root, 10)
root = s.insert(root, 21)
root = s.insert(root, 6)
root = s.insert(root, 3)
root = s.insert(root, 8)
root = s.insert(root, 19)
root = s.insert(root, 24)
root = s.insert(root, 7)
root = s.insert(root, 15)
root = s.insert(root, 22)
root = s.insert(root, 20)
root = s.insert(root, 25)
root = s.delete(root, 3) # where root is leaf node
root = s.delete(root, 8) # where root is left tree
root = s.delete(root, 21) # where root is BST
s.preorder(root)
And here is the code.
class TreeNode():
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class Solution():
def insert(self, root, val):
...
def search(self, root, target):
# Pre-Order
if root is None:
return None
else:
if target == root.val:
return root
elif target < root.val:
return self.search(root.left, target)
else:
return self.search(root.right, target)
def find_max(self, root):
now = root
while now.right:
now = now.right
return now
def delete(self, root, target):
root = self.search(root, target)
if root is None:
return root
else:
if target == root.val:
# when root is a leaf node
if root.left is None and root.right is None:
root = None
return root
elif root.left is None or root.right is None:
# when root is a left tree
if root.left:
root = root.left
return root
# when root is a right tree
else:
root = root.right
return root
# when root is a BST
elif root.left and root.right:
change_value = self.find_max(root.left)
root.val = change_value.val
root.left = self.delete(self, root.left, root.val)
return root
else:
return root
# print the value of BST
def preorder(self, root):
if root is not None:
print(root.val)
self.preorder(root.left)
self.preorder(root.right)
the original BST image: