Invert a binary tree.
'''# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
#16ms, 11MB
class Solution1(object):
def invertTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
def invert(root):
if root:
temp = root.left
root.left = root.right
root.right = temp
if root.left: invert(root.left)
if root.right: invert(root.right)
dump = root
invert(dump)
return root
#28ms, 10.7MB
class Solution2(object):
def invertTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
dump = root
if root:
temp = root.left
root.left = root.right
root.right = temp
if root.left: self.invertTree(root.left)
if root.right: self.invertTree(root.right)
return dump
No comments:
Post a Comment