Skip to content

Instantly share code, notes, and snippets.

@yershalom
Created October 14, 2022 05:58
Show Gist options
  • Save yershalom/d7c3acae109b5d65c5516ae9263fe982 to your computer and use it in GitHub Desktop.
Save yershalom/d7c3acae109b5d65c5516ae9263fe982 to your computer and use it in GitHub Desktop.
Reverse a binary tree to satisfy the ego of a L2 Google engineer
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def reverse_tree(tree):
if tree is None:
return
if tree.left is None and tree.right is None:
return
if tree.left is None:
tree.left = tree.right
tree.right = None
reverse_tree(tree.left)
elif tree.right is None:
tree.right = tree.left
tree.left = None
reverse_tree(tree.right)
else:
tmp = tree.left
tree.left = tree.right
tree.right = tmp
reverse_tree(tree.left)
reverse_tree(tree.right)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment