非递归版本:
1 """ 2 Definition of TreeNode: 3 class TreeNode: 4 def __init__(self, val): 5 self.val = val 6 self.left, self.right = None, None 7 """ 8 9 class Solution: 10 """ 11 @param root: a TreeNode, the root of the binary tree 12 @return: nothing 13 """ 14 def invertBinaryTree(self, root): 15 # write your code here 16 if root == None: 17 return 18 stack = [root] 19 while stack: 20 cur = stack.pop() 21 cur.left, cur.right = cur.right, cur.left 22 if cur.left: 23 stack.append(cur.left) 24 if cur.right: 25 stack.append(cur.right)
递归版本:
1 """ 2 Definition of TreeNode: 3 class TreeNode: 4 def __init__(self, val): 5 self.val = val 6 self.left, self.right = None, None 7 """ 8 9 class Solution: 10 """ 11 @param root: a TreeNode, the root of the binary tree 12 @return: nothing 13 """ 14 def invertBinaryTree(self, root): 15 # write your code here 16 root = self.helper(root) 17 18 def helper(self, root): 19 if root is not None: 20 root.left, root.right = self.helper(root.right), self.helper(root.left) 21 return root