Created
October 14, 2022 05:58
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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