Delete a Binary Tree Flashcards
(1 cards)
1
Q
Deletion in a Binary tree
A
from collections importa deque
class Node:
def__init__(self, d):
self.data = d
self.left = None
self.right = None
def deleteNode(root, val):
if root is None:
return None
queue = deque([root]) target = None #find the target node while queue: curr = queue.popleft() if curr.data == val target = curr break if curr.left: queue.append(curr.left) if curr.right: queue.append(curr.right) if target is None: return root #find the deepest rightmostand its parent last_node = None last_parent = parent if curr.left: queue.append((curr.left, curr)) if curr.right: queue.append((curr.right, curr)) #replace the target value with the last node target.data = lasta_node.data #remove the last node if last_parent: if last_parent.left == last_node last_parent.left = Node else: last_parent.right = Node else: return None return root