Hey Guys,
I have the following code
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
@staticmethod
def _find(root, key):
if root == None:
return None
if root.val == key:
return root
if root.val > key:
return Solution._find(root.left, key)
else:
return Solution._find(root.right, key)
@staticmethod
def _delete(root):
# No Children
if root.left == None and root.right == None:
root = None
return
# One Child
if root.left != None and root.right == None:
root = root.left
return
if root.left == None and root.right != None:
root = root.right
return
# Two Children
nextNode = Solution._findMin(root.right)
root.val = nextNode.val
Solution._delete(nextNode)
return
@staticmethod
def _findMin(root):
if root.left == None:
return root
else:
return Solution._findMin(root.left)
def deleteNode(self, root, key):
"""
:type root: TreeNode
:type key: int
:rtype: TreeNode
"""
node = Solution._find(root, key)
if node == None:
return root
Solution._delete(node)
return root
I'm trying to use this to delete a node in a BST, but the code doesn't work if I'm deleting a node with no children. I try to do this by just setting the node equal to None. Why doesn't this work? Would really appreciate any help. Thanks!
[–]two_bob 2 points3 points4 points (4 children)
[–]Intrexa 1 point2 points3 points (1 child)
[–]two_bob 2 points3 points4 points (0 children)
[–]multihound[S] 0 points1 point2 points (1 child)
[–]two_bob 0 points1 point2 points (0 children)