题目
我的代码(递归)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def invertTree(self, root: TreeNode) -> TreeNode:
if root:
self.invertTree(root.left)
self.invertTree(root.right)
tmp=root.right
root.right=root.left
root.left=tmp
return root
高效方法:
class Solution:
def invertTree(self, root: 'TreeNode') -> 'TreeNode':
if root is None:
return None
root.left, root.right = (self.invertTree(root.right), self.invertTree(root.left),)
return root