if a is None or b is None:
    return
if b.parent == a:
    a, b = b, a
a.parent, b.parent = b.parent, a.parent
a.left, b.left = b.left, a.left
a.right, b.right = b.right, a.right
if b.parent == b:
    b.parent = a
if a.parent is not None:
    if a.parent.left == b:
        a.parent.left = a
else:
    pass
Algorithm to exchange the roles of two randomly chosen nodes from a tree moving pointers