class Solution(object):
def invertTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if root.left != None or root.right!= None:
temp = root.left
root.left = root.right
root.right = temp
if root.left!=None:
self.invertTree(self,root.left)
if root.right!=None:
self.invertTree(self,root.right)
return root
if root
一定要写,因为可能输入的时候是空的,这时候空对象是不可能有left或者right属性的,会报错
class Solution(object):
def invertTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if root:
self.invertTree(root.left)
self.invertTree(root.right)
root.left,root.right = root.right,root.left
return root
class Solution(object):
def invertTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
stack = [root]
while stack:
top = stack.pop()
if top:
top.left,top.right = top.right,top.left
stack.append(top.left)
stack.append(top.right)
return root