Created
August 27, 2015 20:53
-
-
Save thenormalsquid/f6de189aa7c86c35c075 to your computer and use it in GitHub Desktop.
invert_bin_tree
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
# Definition for a binary tree node. | |
# class TreeNode(object): | |
# def __init__(self, x): | |
# self.val = x | |
# self.left = None | |
# self.right = None | |
class Solution(object): | |
def swap_nodes(self, node): | |
tmp = node.right | |
node.right = node.left | |
node.left = tmp | |
def preorder(node): | |
if not(node): | |
return | |
else: | |
self.swap(node) | |
preorder(node.left) | |
preorder(node.right) | |
def invertTree(self, root): | |
""" | |
:type root: TreeNode | |
:rtype: TreeNode | |
""" | |
if(not(root.left or root.right)): | |
return root | |
else: | |
#preorder traversal and swap | |
self.preorder(root) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment